Salome HOME
File naming strategy is set to "asis" and generated number is in the prefix now inste...
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / service / DocumentServiceImpl.java
index df410aa36a93ec9ad76d9e850cf3c87d00402e6d..c8494b13e70cf1fcd931b082cd3b4ca9ba3152ab 100644 (file)
@@ -15,7 +15,6 @@ import java.util.Calendar;
 import java.util.Iterator;
 import java.util.List;
 
-import org.hibernate.Hibernate;
 import org.hibernate.criterion.Criterion;
 import org.hibernate.criterion.Restrictions;
 import org.splat.dal.bo.kernel.Relation;
@@ -30,19 +29,19 @@ import org.splat.dal.bo.som.StampRelation;
 import org.splat.dal.bo.som.Study;
 import org.splat.dal.bo.som.Timestamp;
 import org.splat.dal.bo.som.ValidationStep;
-import org.splat.dal.bo.som.VersionsRelation;
 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;
+import org.splat.dal.dao.som.StudyDAO;
 import org.splat.kernel.InvalidPropertyException;
 import org.splat.kernel.MissedPropertyException;
-import org.splat.kernel.MultiplyDefinedException;
 import org.splat.kernel.NotApplicableException;
+import org.splat.log.AppLogger;
 import org.splat.manox.Reader;
 import org.splat.manox.Toolbox;
 import org.splat.service.technical.ProjectSettingsService;
-import org.splat.service.technical.ProjectSettingsServiceImpl;
 import org.splat.service.technical.RepositoryService;
 import org.splat.service.technical.ProjectSettingsServiceImpl.FileNaming;
 import org.splat.som.Revision;
@@ -56,6 +55,12 @@ import org.springframework.transaction.annotation.Transactional;
  */
 public class DocumentServiceImpl implements DocumentService {
 
+       /**
+        * The logger for the service.
+        */
+       public final static AppLogger LOG = AppLogger
+                       .getLogger(DocumentServiceImpl.class);
+
        /**
         * Injected study service.
         */
@@ -63,7 +68,7 @@ public class DocumentServiceImpl implements DocumentService {
        /**
         * Injected project settings service.
         */
-       private ProjectSettingsService _projectSettingsService;
+       private ProjectSettingsService _projectSettings;
        /**
         * Injected repository service.
         */
@@ -72,6 +77,10 @@ public class DocumentServiceImpl implements DocumentService {
         * Injected document DAO.
         */
        private DocumentDAO _documentDAO;
+       /**
+        * Injected relation DAO.
+        */
+       private RelationDAO _relationDAO;
        /**
         * Injected document type DAO.
         */
@@ -80,6 +89,10 @@ public class DocumentServiceImpl implements DocumentService {
         * Injected file DAO.
         */
        private FileDAO _fileDAO;
+       /**
+        * Injected study DAO.
+        */
+       private StudyDAO _studyDAO;
 
        /**
         * {@inheritDoc}
@@ -87,7 +100,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @see org.splat.service.DocumentService#selectDocument(long)
         */
        @Transactional(readOnly = true)
-       public Document selectDocument(long index) {
+       public Document selectDocument(final long index) {
                return getDocumentDAO().get(index);
        }
 
@@ -97,7 +110,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @see org.splat.service.DocumentService#selectDocument(java.lang.String, java.lang.String)
         */
        @Transactional(readOnly = true)
-       public Document selectDocument(String refid, String version) {
+       public Document selectDocument(final String refid, final String version) {
                Criterion aCondition = Restrictions.and(Restrictions.eq("did", refid),
                                Restrictions.eq("version", version));
                return getDocumentDAO().findByCriteria(aCondition);
@@ -108,19 +121,19 @@ public class DocumentServiceImpl implements DocumentService {
         * 
         * @see org.splat.service.DocumentService#generateDocumentId(org.splat.dal.bo.som.Document, org.splat.dal.bo.som.Document.Properties)
         */
-       public void generateDocumentId(Document aDoc, Properties dprop) {
-               Study owner = null;
-               if (dprop.getOwner() instanceof Study)
-                       owner = (Study) dprop.getOwner();
-               else
-                       owner = ((Scenario) dprop.getOwner()).getOwnerStudy();
+       @Transactional
+       public void generateDocumentId(final Document aDoc, final Properties dprop) {
+               Study owner = dprop.getOwner().getOwnerStudy();
+
+               // Synchronize the object with the current Hibernate session.
+               // owner = getStudyDAO().merge(owner);
 
-               SimpleDateFormat tostring = new SimpleDateFormat("yyyy");
+               SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); // RKV: NOPMD: TODO: Use locale here?
                String year = tostring.format(owner.getDate());
                String filename = generateEncodedName(aDoc, owner);
                String path = owner.getReference();
-               ProjectSettingsService.Step step = ProjectSettingsServiceImpl
-                               .getStep(aDoc.getStep());
+               ProjectSettingsService.Step step = getProjectSettings().getStep(
+                               aDoc.getStep());
                aDoc.setDid(new StringBuffer(path).append(".%").append(
                                Document.suformat).toString()); // Document reference
                path = new StringBuffer(year).append("/").append(path).append("/")
@@ -130,6 +143,8 @@ public class DocumentServiceImpl implements DocumentService {
                                .append(aDoc.getFile().getFormat()) // File name and extension
                                .toString();
                aDoc.getFile().changePath(path);
+               owner = getStudyDAO().merge(owner);
+               // getStudyDAO().update(owner);
        }
 
        /**
@@ -141,7 +156,7 @@ public class DocumentServiceImpl implements DocumentService {
         *            the study
         * @return document reference name
         */
-       private String generateEncodedName(Document aDoc, Study scope) {
+       private String generateEncodedName(final Document aDoc, final Study scope) {
                StringBuffer encoding = new StringBuffer();
                FileNaming scheme = getProjectSettings().getFileNamingScheme();
                DecimalFormat tostring = new DecimalFormat(Document.suformat);
@@ -149,11 +164,11 @@ public class DocumentServiceImpl implements DocumentService {
                int number = getStudyService().generateLocalIndex(scope);
 
                if (scheme == FileNaming.encoded) {
-                       encoding.append(scope.getReference()).append(".").append(
+                       encoding.append(scope.getReference()).append("_").append(
                                        tostring.format(number));
                } else { // title and (temporarily) asis
-                       encoding.append(aDoc.getTitle()).append(".").append(
-                                       tostring.format(number));
+                       encoding.append("_").append(tostring.format(number)).append(
+                                       aDoc.getFile().getName());
                }
                return encoding.toString();
        }
@@ -167,13 +182,14 @@ public class DocumentServiceImpl implements DocumentService {
         *            the study
         * @return file name
         */
-       private String getEncodedRootName(Document aDoc, Study scope) {
+       private String getEncodedRootName(final Document aDoc, final Study scope) {
                FileNaming scheme = getProjectSettings().getFileNamingScheme();
 
-               if (scheme == FileNaming.encoded)
+               if (scheme == FileNaming.encoded) {
                        return scope.getReference();
-               else
+               } else {
                        return aDoc.getTitle();
+               }
        }
 
        /**
@@ -182,18 +198,22 @@ public class DocumentServiceImpl implements DocumentService {
         * @see org.splat.service.DocumentService#initialize(org.splat.dal.bo.som.Document, org.splat.dal.bo.som.Document.Properties)
         */
        @Transactional
-       public void initialize(Document aDoc, Properties dprop)
+       public void initialize(final Document aDoc, final Properties dprop)
                        throws MissedPropertyException, InvalidPropertyException,
                        NotApplicableException {
-               if (!aDoc.isUndefined())
+               if (!aDoc.isUndefined()) {
                        throw new NotApplicableException(
                                        "Cannot initialize an existing Document");
-               if (dprop.getName() == null)
+               }
+               if (dprop.getName() == null) {
                        throw new MissedPropertyException("name");
-               if (dprop.getName().length() == 0)
+               }
+               if (dprop.getName().length() == 0) {
                        throw new InvalidPropertyException("name");
-               if (dprop.getOwner() == null)
+               }
+               if (dprop.getOwner() == null) {
                        throw new MissedPropertyException("owner");
+               }
                // if (dprop.owner instanceof Study && !ProjectSettings.getStep(step).appliesTo(Study.class)) {
                // throw new InvalidPropertyException("step");
                // }
@@ -201,8 +221,9 @@ public class DocumentServiceImpl implements DocumentService {
                aDoc.getFile().changePath(
                                aDoc.getFile().getRelativePath().replace("%n",
                                                getEncodedRootName(aDoc, (Study) dprop.getOwner())));
-               if (aDoc.getHistory() == -1)
+               if (aDoc.getHistory() == -1) {
                        aDoc.setHistory(0);
+               }
                if (dprop.getDate() == null) {
                        Calendar current = Calendar.getInstance();
                        aDoc.setLastModificationDate(current.getTime()); // Today
@@ -217,15 +238,16 @@ public class DocumentServiceImpl implements DocumentService {
         * 
         * @see org.splat.service.DocumentService#getSaveDirectory(org.splat.dal.bo.som.Document)
         */
-       public java.io.File getSaveDirectory(Document aDoc) {
+       public java.io.File getSaveDirectory(final Document aDoc) {
                String mypath = getRepositoryService().getRepositoryVaultPath()
                                + aDoc.getSourceFile().getRelativePath();
                String[] table = mypath.split("/");
 
                // Cutting the filename
                StringBuffer path = new StringBuffer(table[0]);
-               for (int i = 1; i < table.length - 1; i++)
+               for (int i = 1; i < table.length - 1; i++) {
                        path = path.append("/").append(table[i]);
+               }
                return new java.io.File(path.append("/").toString());
        }
 
@@ -236,21 +258,25 @@ public class DocumentServiceImpl implements DocumentService {
         *            the file to parse
         * @return the extracted properties
         */
-       public Properties extractProperties(java.io.File file) {
+       public Properties extractProperties(final java.io.File file) {
                Properties fprop = new Properties();
                Reader tool = Toolbox.getReader(file);
                String value;
-               if (tool != null)
+               if (tool != null) {
                        try {
                                value = tool.extractProperty("title");
-                               if (value != null)
+                               if (value != null) {
                                        fprop.setName(value);
+                               }
 
                                value = tool.extractProperty("reference");
-                               if (value != null)
+                               if (value != null) {
                                        fprop.setReference(value);
+                               }
                        } catch (Exception e) {
+                               LOG.debug(e.getMessage(), e);
                        }
+               }
                return fprop;
        }
 
@@ -263,7 +289,8 @@ public class DocumentServiceImpl implements DocumentService {
         *            the format
         * @return the created "Converts" relation
         */
-       public ConvertsRelation attach(Document aDoc, String format) {
+       @Transactional
+       public ConvertsRelation attach(final Document aDoc, final String format) {
                return attach(aDoc, format, null);
        }
 
@@ -279,21 +306,18 @@ public class DocumentServiceImpl implements DocumentService {
         * @return the created "Converts" relation
         */
        @Transactional
-       public ConvertsRelation attach(Document aDoc, String format,
-                       String description) {
+       public ConvertsRelation attach(final Document aDoc, final String format,
+                       final String description) {
                String path = aDoc.getRelativePath();
                File export = new File(path + "." + format);
                ConvertsRelation attach = new ConvertsRelation(aDoc, export,
                                description);
 
-               // RKV Session session = Database.getSession();
-               // 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;
        }
@@ -309,24 +333,23 @@ public class DocumentServiceImpl implements DocumentService {
         *            the original document
         * @return true if the new reference is set
         */
-       public boolean buildReferenceFrom(Document aDoc, ProjectElement scope,
-                       Document lineage) {
-               if (aDoc.getProgressState() != ProgressState.inWORK)
-                       return false;
-               Study owner = null;
-               Scenario context = null;
-               if (scope instanceof Study)
-                       owner = (Study) scope;
-               else {
-                       context = ((Scenario) scope);
-                       owner = context.getOwnerStudy();
-               }
-               aDoc.setDid(lineage.getDid());
-               if (context != null && (lineage.isVersioned() || owner.shares(lineage))) {
-                       aDoc.setVersion(new Revision(aDoc.getVersion()).setBranch(
-                                       context.getReference()).toString());
+       public boolean buildReferenceFrom(final Document aDoc,
+                       final ProjectElement scope, final Document lineage) {
+               boolean res = (aDoc.getProgressState() == ProgressState.inWORK);
+               if (res) {
+                       Study owner = scope.getOwnerStudy();
+                       Scenario context = null;
+                       if (scope instanceof Scenario) {
+                               context = ((Scenario) scope);
+                       }
+                       aDoc.setDid(lineage.getDid());
+                       if (context != null
+                                       && (lineage.isVersioned() || owner.shares(lineage))) {
+                               aDoc.setVersion(new Revision(aDoc.getVersion()).setBranch(
+                                               context.getReference()).toString());
+                       }
                }
-               return true;
+               return res;
        }
 
        /**
@@ -338,10 +361,11 @@ public class DocumentServiceImpl implements DocumentService {
         *            the study
         * @return true if the new reference is set
         */
-       public boolean buildReferenceFrom(Document aDoc, Study scope) {
+       public boolean buildReferenceFrom(final Document aDoc, final Study scope) {
                if (aDoc.getProgressState() != ProgressState.inWORK
-                               && aDoc.getProgressState() != ProgressState.EXTERN)
+                               && aDoc.getProgressState() != ProgressState.EXTERN) {
                        return false;
+               }
                DecimalFormat tostring = new DecimalFormat(Document.suformat);
 
                aDoc.setDid(aDoc.getDid().replace("%" + Document.suformat,
@@ -357,7 +381,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @return true if demoting succeeded
         */
        @Transactional
-       public boolean demote(Document aDoc) {
+       public boolean demote(final Document aDoc) {
                ValidationStep torem;
 
                if (aDoc.getProgressState() == ProgressState.inCHECK) {
@@ -374,10 +398,12 @@ public class DocumentServiceImpl implements DocumentService {
                for (Iterator<Relation> i = aDoc.getAllRelations().iterator(); i
                                .hasNext();) {
                        Relation link = i.next();
-                       if (!(link instanceof StampRelation))
+                       if (!(link instanceof StampRelation)) {
                                continue;
-                       if (((StampRelation) link).getStampType() != torem)
+                       }
+                       if (((StampRelation) link).getStampType() != torem) {
                                continue;
+                       }
                        i.remove();
                        break;
                }
@@ -395,7 +421,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @return true if promotion succeeded
         */
        @Transactional
-       public boolean promote(Document aDoc, Timestamp stamp) {
+       public boolean promote(final Document aDoc, final Timestamp stamp) {
                ProgressState newstate = null;
 
                if (aDoc.getProgressState() == ProgressState.inWORK) {
@@ -428,7 +454,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @see #release()
         */
        @Transactional
-       public void hold(Document aDoc) {
+       public void hold(final Document aDoc) {
                aDoc.setCountag(aDoc.getCountag() + 1);
                if (aDoc.isSaved()) {
                        getDocumentDAO().update(aDoc);
@@ -443,10 +469,10 @@ public class DocumentServiceImpl implements DocumentService {
         * @see #hold()
         */
        @Transactional
-       public void release(Document aDoc) {
+       public void release(final Document aDoc) {
                aDoc.setCountag(aDoc.getCountag() - 1);
                if (aDoc.isSaved()) {
-                       getDocumentDAO().update(aDoc);
+                       getDocumentDAO().merge(aDoc);
                }
        }
 
@@ -461,10 +487,11 @@ public class DocumentServiceImpl implements DocumentService {
         *             if the new title is empty
         */
        @Transactional
-       public void rename(Document aDoc, String title)
+       public void rename(final Document aDoc, final String title)
                        throws InvalidPropertyException {
-               if (title.length() == 0)
+               if (title.length() == 0) {
                        throw new InvalidPropertyException("name");
+               }
 
                Calendar current = Calendar.getInstance();
                aDoc.setTitle(title);
@@ -480,11 +507,12 @@ public class DocumentServiceImpl implements DocumentService {
         * @param newvers
         *            the new version
         */
-       public void updateAs(Document aDoc, Revision newvers) {
+       public void updateAs(final Document aDoc, final Revision newvers) {
                aDoc.setVersion(newvers.setBranch(aDoc.getVersion()).toString()); // Branch names are propagated by the versionning
                ProgressState newstate = ProgressState.inCHECK;
-               if (newvers.isMinor())
+               if (newvers.isMinor()) {
                        newstate = ProgressState.inWORK;
+               }
                aDoc.setProgressState(null); // Just to tell updateAs(state) to not increment the version number
                updateAs(aDoc, newstate);
        }
@@ -498,36 +526,31 @@ public class DocumentServiceImpl implements DocumentService {
         *            the new state
         */
        @Transactional
-       public void updateAs(Document aDoc, ProgressState state) {
+       public void updateAs(final Document aDoc, final ProgressState state) {
                Document previous = null;
 
                // Set of version number
                if (state == ProgressState.EXTERN) {
-                       if (aDoc.getProgressState() != ProgressState.EXTERN)
+                       if (aDoc.getProgressState() != ProgressState.EXTERN) {
                                aDoc.setVersion(null); // Strange use-case...
+                       }
                } else {
                        Revision myvers = new Revision(aDoc.getVersion());
                        if (!myvers.isNull()) { // Versionning context
-                               for (Iterator<Relation> i = aDoc.getAllRelations().iterator(); i
-                                               .hasNext();) {
-                                       Relation link = i.next();
-                                       if (!link.getClass().equals(VersionsRelation.class))
-                                               continue;
-                                       previous = (Document) link.getTo(); // Versioned document
-                                       break;
-                               }
+                               previous = aDoc.getPreviousVersion();
                        }
-                       if (aDoc.getProgressState() != null)
+                       if (aDoc.getProgressState() != null) {
                                myvers.incrementAs(state); // Incrementation if the reversion number is not imposed
+                       }
                        aDoc.setVersion(myvers.toString());
                }
-               // Update this document and the previous version, if exit
+               // Update this document and the previous version, if exist
                if (previous != null) {
                        previous.setHistory(previous.getHistory() + 1);
-                       getDocumentDAO().update(previous);
+                       getDocumentDAO().merge(previous);
                }
                aDoc.setProgressState(state);
-               getDocumentDAO().update(aDoc);
+               // RKV: getDocumentDAO().update(aDoc);
        }
 
        // protected void upgrade () {
@@ -560,14 +583,32 @@ public class DocumentServiceImpl implements DocumentService {
         * @see #isStepResult()
         * @see #isResultOf(org.splat.service.technical.ProjectSettingsServiceImpl.Step)
         */
-       public boolean isStudyResult(DocumentType aType) {
-               // -------------------------------
+       public boolean isStudyResult(final DocumentType aType) {
                List<ProjectSettingsService.Step> step = getProjectSettings()
                                .getAllSteps();
                ProjectSettingsService.Step lastep = step.get(step.size() - 1);
                return (aType.isResultOf(lastep));
        }
 
+       /**
+        * Get document by its path.
+        * 
+        * @param path
+        *            the document path
+        * @return the document if found or null
+        */
+       @Transactional(readOnly = true)
+       public Document getDocumentByPath(String path) {
+               String[] parse = path.split("'");
+
+               path = parse[0];
+               for (int i = 1; i < parse.length; i++) {
+                       path = path + "''" + parse[i];
+               }
+               Criterion aCondition = Restrictions.eq("path", path);
+               return getDocumentDAO().findByCriteria(aCondition);
+       }
+
        /**
         * Get the studyService.
         * 
@@ -583,7 +624,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @param studyService
         *            the studyService to set
         */
-       public void setStudyService(StudyService studyService) {
+       public void setStudyService(final StudyService studyService) {
                _studyService = studyService;
        }
 
@@ -593,7 +634,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @return Project settings service
         */
        private ProjectSettingsService getProjectSettings() {
-               return _projectSettingsService;
+               return _projectSettings;
        }
 
        /**
@@ -602,8 +643,9 @@ public class DocumentServiceImpl implements DocumentService {
         * @param projectSettingsService
         *            project settings service
         */
-       public void setProjectSettings(ProjectSettingsService projectSettingsService) {
-               _projectSettingsService = projectSettingsService;
+       public void setProjectSettings(
+                       final ProjectSettingsService projectSettingsService) {
+               _projectSettings = projectSettingsService;
        }
 
        /**
@@ -621,7 +663,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @param documentDAO
         *            the documentDAO to set
         */
-       public void setDocumentDAO(DocumentDAO documentDAO) {
+       public void setDocumentDAO(final DocumentDAO documentDAO) {
                _documentDAO = documentDAO;
        }
 
@@ -640,7 +682,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @param repositoryService
         *            the repositoryService to set
         */
-       public void setRepositoryService(RepositoryService repositoryService) {
+       public void setRepositoryService(final RepositoryService repositoryService) {
                _repositoryService = repositoryService;
        }
 
@@ -659,7 +701,7 @@ public class DocumentServiceImpl implements DocumentService {
         * @param documentTypeDAO
         *            the documentTypeDAO to set
         */
-       public void setDocumentTypeDAO(DocumentTypeDAO documentTypeDAO) {
+       public void setDocumentTypeDAO(final DocumentTypeDAO documentTypeDAO) {
                _documentTypeDAO = documentTypeDAO;
        }
 
@@ -678,8 +720,46 @@ public class DocumentServiceImpl implements DocumentService {
         * @param fileDAO
         *            the fileDAO to set
         */
-       public void setFileDAO(FileDAO fileDAO) {
+       public void setFileDAO(final FileDAO fileDAO) {
                _fileDAO = fileDAO;
        }
 
+       /**
+        * Get the studyDAO.
+        * 
+        * @return the studyDAO
+        */
+       public StudyDAO getStudyDAO() {
+               return _studyDAO;
+       }
+
+       /**
+        * Set the studyDAO.
+        * 
+        * @param studyDAO
+        *            the studyDAO to set
+        */
+       public void setStudyDAO(final StudyDAO studyDAO) {
+               _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;
+       }
+
 }