Salome HOME
Fix:
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / service / StudyServiceImpl.java
index 374c04317d8ef27faca3eda61eab6778488a4e4a..5657ba53c9d3aefd859f902a2283aec58a2e91eb 100644 (file)
 /*****************************************************************************
- * Company         EURIWARE
+ * Company         OPEN CASCADE
  * Application     SIMAN
- * File            $Id$ 
- * Creation date   06.10.2012
- * @author         $Author$
- * @version        $Revision$
+ * File            Id: 
+ * Creation date   02.10.2012
+ * @author         Author: Maria KRUCHININA
+ * @version        Revision: 
  *****************************************************************************/
 
 package org.splat.service;
 
 import java.io.IOException;
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
 import java.util.Date;
-import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
-import org.apache.log4j.Logger;
-import org.hibernate.Session;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.store.FSDirectory;
+import org.hibernate.Criteria;
+import org.hibernate.criterion.DetachedCriteria;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.Restrictions;
 import org.splat.dal.bo.kernel.Relation;
 import org.splat.dal.bo.kernel.User;
 import org.splat.dal.bo.som.ActorRelation;
 import org.splat.dal.bo.som.ContributorRelation;
 import org.splat.dal.bo.som.DescriptionAttribute;
-import org.splat.dal.bo.som.Document;
 import org.splat.dal.bo.som.DocumentType;
 import org.splat.dal.bo.som.IDBuilder;
 import org.splat.dal.bo.som.KnowledgeElement;
-import org.splat.dal.bo.som.KnowledgeElementType;
 import org.splat.dal.bo.som.ProgressState;
 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;
 import org.splat.dal.bo.som.ValidationCycle;
 import org.splat.dal.bo.som.ValidationCycleRelation;
+import org.splat.dal.bo.som.ValidationStep;
 import org.splat.dal.bo.som.Visibility;
 import org.splat.dal.bo.som.Study.Properties;
-import org.splat.dal.dao.som.Database;
+import org.splat.dal.bo.som.ValidationCycle.Actor;
+import org.splat.dal.dao.som.DescriptionAttributeDAO;
+import org.splat.dal.dao.som.DocumentDAO;
+import org.splat.dal.dao.som.DocumentTypeDAO;
+import org.splat.dal.dao.som.IDBuilderDAO;
+import org.splat.dal.dao.som.PublicationDAO;
+import org.splat.dal.dao.som.ScenarioDAO;
+import org.splat.dal.dao.som.StudyDAO;
+import org.splat.dal.dao.som.UsedByRelationDAO;
+import org.splat.dal.dao.som.ValidationCycleDAO;
+import org.splat.exception.BusinessException;
+import org.splat.exception.InvalidParameterException;
 import org.splat.kernel.InvalidPropertyException;
 import org.splat.kernel.MissedPropertyException;
 import org.splat.kernel.MultiplyDefinedException;
-import org.splat.kernel.UserDirectory;
+import org.splat.log.AppLogger;
+import org.splat.service.dto.UserDTO;
 import org.splat.service.technical.IndexService;
 import org.splat.service.technical.ProjectSettingsService;
+import org.splat.service.technical.ProjectSettingsServiceImpl;
+import org.splat.service.technical.RepositoryService;
 import org.splat.som.Revision;
+import org.splat.util.BeanHelper;
+import org.springframework.transaction.annotation.Transactional;
 
 /**
- * @author RKV
+ * This class defines all methods for creation, modification the study.
+ * 
+ * @author Maria KRUCHININA
  * 
  */
 public class StudyServiceImpl implements StudyService {
 
-       public final static Logger logger = Logger.getLogger(org.splat.service.StudyServiceImpl.class);
+       /**
+        * logger for the service.
+        */
+       public final static AppLogger LOG = AppLogger
+                       .getLogger(StudyServiceImpl.class);
+       /**
+        * "studyId" parameter name.
+        */
+       public final static String PARAM_STUDY_ID = "studyId";
 
+       /**
+        * Injected index service.
+        */
        private IndexService _indexService;
 
+       /**
+        * Injected step service.
+        */
        private StepService _stepService;
 
-       private ScenarioService _scenarioService;
-
-       private ProjectSettingsService _projectSettingsService;
+       /**
+        * Injected project service.
+        */
+       private ProjectSettingsService _projectSettings;
 
+       /**
+        * Injected project element service.
+        */
        private ProjectElementService _projectElementService;
 
-       public Study createStudy(Study.Properties sprop)
+       /**
+        * Injected study DAO.
+        */
+       private StudyDAO _studyDAO;
+
+       /**
+        * Injected usedBy relations DAO.
+        */
+       private UsedByRelationDAO _usedByRelationDAO;
+
+       /**
+        * Injected scenario DAO.
+        */
+       private ScenarioDAO _scenarioDAO;
+
+       /**
+        * Injected validation cycle DAO.
+        */
+       private ValidationCycleDAO _validationCycleDAO;
+
+       /**
+        * Injected IDBuilder DAO.
+        */
+       private IDBuilderDAO _iDBuilderDAO;
+
+       /**
+        * Injected document type service.
+        */
+       private DocumentTypeService _documentTypeService;
+
+       /**
+        * Injected user service.
+        */
+       private UserService _userService;
+
+       /**
+        * Injected publication DAO.
+        */
+       private PublicationDAO _publicationDAO;
+
+       /**
+        * Injected repository service.
+        */
+       private RepositoryService _repositoryService;
+
+       /**
+        * Injected document DAO.
+        */
+       private DocumentDAO _documentDAO;
+
+       /**
+        * Injected description attribute DAO.
+        */
+       private DescriptionAttributeDAO _descriptionAttributeDAO;
+       /**
+        * Injected document type DAO.
+        */
+       private DocumentTypeDAO _documentTypeDAO;
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#selectStudy(long)
+        */
+       @Transactional
+       public Study selectStudy(final long index) {
+               Study result = getStudyDAO().get(index);
+               if (result != null) {
+                       loadWorkflow(result);
+               }
+               return result;
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#removeStudy(long)
+        */
+       @Transactional
+       public void removeStudy(final Long index) {
+               Study study = getStudyDAO().get(index);
+               Set<org.splat.dal.bo.som.Document> docums = new HashSet<org.splat.dal.bo.som.Document>();
+               if (study != null) {
+                       // Select all documents published in the study and study's scenarios.
+                       DetachedCriteria query = DetachedCriteria.forClass(
+                                       Publication.class, "pub");
+                       query
+                                       .createCriteria("pub.owner", "projelem",
+                                                       Criteria.INNER_JOIN)
+                                       .createAlias("projelem.owner", "study", Criteria.LEFT_JOIN)
+                                       .add(
+                                                       Restrictions
+                                                                       .or(Restrictions.eq("projelem.rid", index),
+                                                                                       Restrictions.eq("study.rid", index)))
+                                       .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
+
+                       if (LOG.isDebugEnabled()) {
+                               LOG.debug("Find study documents: " + query.toString());
+                       }
+                       for (Publication pub : getPublicationDAO().getFilteredList(query)) {
+                               docums.add(pub.value());
+                               // Find also all previous versions of the document
+                               for (org.splat.dal.bo.som.Document prev = pub.value()
+                                               .getPreviousVersion(); prev != null; prev = prev
+                                               .getPreviousVersion()) {
+                                       docums.add(prev);
+                               }
+                       }
+
+                       // Delete the study with its relations, scenarios and publications
+                       getStudyDAO().delete(study);
+
+                       // Remove all relations of study documents
+                       for (org.splat.dal.bo.som.Document doc : docums) {
+                               LOG.debug("Found doc: " + doc.getTitle() + " ["
+                                               + doc.getReference() + "]" + " [" + doc.getRid() + "]");
+                               doc.getAllRelations().clear();
+                       }
+                       getDocumentDAO().flush();
+
+                       // Remove all documents of the study
+                       for (org.splat.dal.bo.som.Document doc : docums) {
+                               LOG.debug("Remove doc: " + doc.getTitle() + " ["
+                                               + doc.getReference() + "]" + " [" + doc.getRid() + "]");
+                               getDocumentDAO().delete(doc);
+                       }
+               }
+       }
+
+       /**
+        * Get study by its reference.
+        * 
+        * @param refid
+        *            the study reference
+        * @return found study or null
+        */
+       @Transactional(readOnly = true)
+       public Study selectStudy(final String refid) {
+               Study result = getStudyDAO().findByCriteria(
+                               Restrictions.eq("sid", refid));
+               loadWorkflow(result);
+               return result;
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#createStudy(org.splat.dal.bo.som.Study.Properties)
+        */
+       @Transactional
+       public Study createStudy(final Study.Properties sprop)
                        throws MissedPropertyException, InvalidPropertyException,
-                       MultiplyDefinedException, RuntimeException {
+                       MultiplyDefinedException {
                sprop.setReference(getProjectSettings().getReferencePattern());
                Study study = new Study(sprop);
 
                buildReference(study);
-               Database.getSession().save(study); // TODO: use StudyDAO and throw out Database.
-               try {
-                       IndexService lucin = getIndex();
-                       lucin.add(study);
-               } catch (IOException error) {
-                       logger.error("Unable to index the study '" + study.getIndex()
-                                       + "', reason:", error);
-                       // Continue and try to index later
-               }
+               getStudyDAO().create(study);
+               // try {
+               // IndexService lucin = getIndex();
+               // lucin.add(study);
+               // } catch (IOException error) {
+               // LOG.error("Unable to index the study '" + study.getIndex()
+               // + "', reason:", error);
+               // // Continue and try to index later
+               // }
                return study;
        }
 
-       public IndexService getIndex() throws IOException {
-               IndexService lucin = getIndexService();
-               if (!lucin.exists())
-                       lucin.create(); // Happens when re-indexing all studies
-               return lucin;
-       }
-
-       public SimulationContext addProjectContext(Study aStudy,
-                       SimulationContext.Properties cprop) throws MissedPropertyException,
-                       InvalidPropertyException, MultiplyDefinedException,
-                       RuntimeException {
-               // -------------------------------------------------------------------------------
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext.Properties)
+        */
+       @Transactional
+       public SimulationContext addProjectContext(final Study aStudy,
+                       final SimulationContext.Properties cprop)
+                       throws MissedPropertyException, InvalidPropertyException,
+                       MultiplyDefinedException {
                SimulationContext added = getStepService().addSimulationContext(
                                getProjectElementService().getFirstStep(aStudy), cprop);
                update(aStudy);
@@ -101,376 +296,1355 @@ public class StudyServiceImpl implements StudyService {
        }
 
        /**
-        * @return
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#addProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
         */
-       public StepService getStepService() {
-               return _stepService;
-       }
-
-       public void setStepService(StepService stepService) {
-               _stepService = stepService;
-       }
-
-       public SimulationContext addProjectContext(Study aStudy,
-                       SimulationContext context) {
-               // ----------------------------------------------------------------------
+       @Transactional
+       public SimulationContext addProjectContext(final Study aStudy,
+                       final SimulationContext context) {
                SimulationContext added = getStepService().addSimulationContext(
                                getProjectElementService().getFirstStep(aStudy), context);
                update(aStudy);
                return added;
        }
 
-       public boolean addContributor(Study aStudy, User user) {
-               // -----------------------------------------
-               List<User> contributor = aStudy.getModifiableContributors(); // Initializes contributor
-               for (Iterator<User> i = contributor.iterator(); i.hasNext();) {
-                       User present = i.next();
-                       if (present.equals(user))
-                               return false;
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#addContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User)
+        */
+       @Transactional
+       public boolean addContributor(final Study aStudy, final User user) {
+               List<User> contributors = getModifiableContributors(aStudy); // Initializes contributor
+
+               if (contributors.contains(user)) {
+                       return false;
+               }
+
+               // Remove user from readers
+               try {
+                       List<UserDTO> readers = getReaders(aStudy.getIndex());
+                       for (UserDTO reader : readers) {
+                               if (reader.getIndex() == user.getIndex()) {
+                                       // user must be the actual user in the relationship object in the aStudy object for this to work
+                                       aStudy.removeRelation(ReaderRelation.class, user);
+                               }
+                       }
+               } catch (InvalidParameterException e) {
+                       LOG.error(e.getMessage(), e);
                }
-               boolean absent = aStudy.getModifiableActors().add(user); // User may already be a reviewer or an approver
+
+               boolean absent = getModifiableActors(aStudy).add(user); // User may already be a reviewer or an approver
 
                aStudy.addRelation(new ContributorRelation(aStudy, user));
-               if (absent)
+               if (absent) {
                        update(aStudy); // Else, useless to re-index the study
-               contributor.add(user);
+               }
                return true;
        }
 
        /**
-        * Moves this study from the Public to the Reference area of the repository. For being moved to the Reference area, the study must
-        * previously be approved.
+        * {@inheritDoc}
         * 
-        * @return true if the move succeeded.
-        * @see #moveToPublic()
-        * @see #isPublic()
-        * @see Publication#approve(Date)
+        * @see org.splat.service.StudyService#update(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.Study.Properties)
         */
-       public boolean moveToReference(Study aStudy) {
-               // ---------------------------------
-               if (aStudy.getProgressState() != ProgressState.APPROVED)
-                       return false;
-               if (aStudy.getVisibility() != Visibility.PUBLIC)
-                       return false;
-
-               aStudy.setVisibility(Visibility.REFERENCE);
-               if (update(aStudy)) {
-                       return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
-               }
-               return false;
-       }
-
-       public boolean update(Study aStudy, Properties sprop)
+       @Transactional
+       public boolean update(final Study aStudy, final Properties sprop)
                        throws InvalidPropertyException {
-               if (sprop.getTitle() != null)
+               if (sprop.getTitle() != null) {
                        aStudy.setTitle(sprop.getTitle());
-               if (sprop.getSummary() != null)
+               }
+               if (sprop.getSummary() != null) {
                        aStudy.setAttribute(new DescriptionAttribute(aStudy, sprop
                                        .getSummary()));
+               }
                // TODO: To be completed
                return update(aStudy);
        }
 
-       public boolean buildReference(Study aStudy) {
-               String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
-               IDBuilder tool = Database.selectIDBuilder(aStudy.getDate());
-               if (tool == null) {
-                       tool = new IDBuilder(aStudy.getDate());
-                       Database.getSession().save(tool);
-               }
-               aStudy.setReference(tool.buildReference(pattern, aStudy));
-               return true;
-       }
-
-       public boolean publishes(Study aStudy, Document doc) {
-               // ---------------------------------------
-               if (!aStudy.publishes(doc)) {
-                       Scenario[] scene = aStudy.getScenarii();
-                       for (int i = 0; i < scene.length; i++) {
-                               if (scene[i].publishes(doc))
-                                       return true;
-                       }
-               }
-               return false;
-       }
-
-       public boolean removeContributor(Study aStudy, User... users) {
-               // ------------------------------------------------
-               List<User> contributor = aStudy.getModifiableContributors(); // Initializes contributor
+       /**
+        * Check if the document is published in the study.
+        * 
+        * @param aStudy
+        *            the study
+        * @param doc
+        *            the document
+        * @return true if the document is published in the study
+        */
+       /*
+        * private boolean publishes(final Study aStudy, final Document doc) { if (!aStudy.publishes(doc)) { Scenario[] scene =
+        * aStudy.getScenarii(); for (int i = 0; i < scene.length; i++) { if (scene[i].publishes(doc)) { return true; } } } return false; }
+        */
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#removeContributor(org.splat.dal.bo.som.Study, org.splat.dal.bo.kernel.User[])
+        */
+       @Transactional
+       public boolean removeContributor(final Study aStudy, final User... users) {
+               List<User> contributors = getModifiableContributors(aStudy); // Initializes contributor
                Boolean done = false;
-               for (int i = 0; i < users.length; i++) {
-                       User user = users[i];
-                       for (Iterator<User> j = contributor.iterator(); j.hasNext();) {
-                               User present = j.next();
-                               if (!present.equals(user))
-                                       continue;
-
+               for (User user : users) {
+                       if (contributors.contains(user)) {
                                aStudy.removeRelation(ContributorRelation.class, user);
-                               j.remove(); // Updates the contributor shortcut
+                               contributors.remove(user);
                                done = true;
-                               break;
                        }
                }
-               if (done)
+               if (done) {
                        update(aStudy);
+               }
                return done;
        }
 
-       public boolean removeProjectContext(Study aStudy, SimulationContext context) {
-               // ---------------------------------------------------------------
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#removeProjectContext(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.SimulationContext)
+        */
+       @Transactional
+       public boolean removeProjectContext(final Study aStudy,
+                       final SimulationContext context) {
                boolean done = getStepService().removeSimulationContext(
                                getProjectElementService().getFirstStep(aStudy), context);
                update(aStudy);
                return done;
        }
 
-       public void setValidationCycle(Study aStudy, DocumentType type,
-                       ValidationCycle.Properties vprop) {
-               HashMap<String, ValidationCycle> validactor = aStudy
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#setValidationCycle(org.splat.dal.bo.som.Study, org.splat.dal.bo.som.DocumentType,
+        *      org.splat.dal.bo.som.ValidationCycle.Properties)
+        */
+       @Transactional
+       public void setValidationCycle(final Study aStudyDTO,
+                       final DocumentType type, final ValidationCycle.Properties vprop) {
+               Map<String, ValidationCycle> validactor = aStudyDTO
                                .getValidationCycles();
-               if (validactor == null)
-                       aStudy.setShortCuts(); // Initializes validactor and actor
+               if (validactor == null) {
+                       setShortCuts(aStudyDTO); // Initializes validactor and actor
+               }
+
+               Study aStudy = selectStudy(aStudyDTO.getIndex());
 
                String cname = type.getName();
                ValidationCycle cycle = validactor.get(cname);
 
                if (cycle != null && cycle.isAssigned()) {
-                       cycle.resetActors(vprop);
-               } else
+                       resetActors(cycle, vprop);
+               } else {
                        try {
                                cycle = new ValidationCycle(aStudy, vprop.setDocumentType(type));
 
+                               getValidationCycleDAO().create(cycle); // RKV
+
                                ValidationCycleRelation link = cycle.getContext();
                                aStudy.addRelation(link);
+                               getValidationCycleDAO().flush();
+                               aStudyDTO.getAllRelations().add(link); // RKV
+
                                validactor.put(cname, link.getTo()); // Replaces the cycle if exists as default,
-                       } catch (Exception error) {
-                               logger.error("Unable to re-index Knowledge Elements, reason:",
-                                               error);
+                       } catch (BusinessException error) {
+                               LOG.error("Unable to create validation cycle, reason:", error);
                                return;
                        }
-               resetActorsShortCut(aStudy);
-               update(aStudy); // Re-index the study, just in case
-       }
-
-       private void resetActorsShortCut(Study aStudy) {
-               aStudy.getModifiableActors().clear();
-               // Get all actors involved in validation cycles
-               for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
-                               .values().iterator(); i.hasNext();) {
-                       ValidationCycle cycle = i.next();
-                       User[] user = cycle.getAllActors();
-                       for (int j = 0; j < user.length; j++)
-                               aStudy.getModifiableActors().add(user[j]);
-               }
-               // Get all other actors
-               for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
-                               .hasNext();) {
-                       Relation link = i.next();
-                       Class<?> kindof = link.getClass().getSuperclass();
-                       if (!kindof.equals(ActorRelation.class))
-                               continue;
-                       aStudy.getModifiableActors().add(((ActorRelation) link).getTo());
                }
+               resetActorsShortCut(aStudyDTO);
+               update(aStudy); // Re-index the study, just in case
        }
 
        /**
-        * Demotes this study from In-Check to In-Draft then In-Work states. This function is called internally when demoting the final result
-        * document of the study.
+        * {@inheritDoc}
         * 
-        * @return true if the demotion succeeded.
+        * @see org.splat.service.StudyService#generateLocalIndex(org.splat.dal.bo.som.Study)
         */
-       public boolean demote(Study aStudy) {
-               // ---------------------------
-               if (aStudy.getProgressState() == ProgressState.inCHECK)
-                       aStudy.setProgressState(ProgressState.inDRAFT);
-               else if (aStudy.getProgressState() == ProgressState.inDRAFT)
-                       aStudy.setProgressState(ProgressState.inWORK);
-               else
-                       return false;
-               return update(aStudy);
-       }
-
-       public int generateLocalIndex(Study aStudy) {
+       @Transactional
+       public int generateLocalIndex(final Study aStudy) {
                aStudy.setLastLocalIndex(aStudy.getLastLocalIndex() + 1);
-               Database.getSession().update(this);
                return aStudy.getLastLocalIndex();
        }
 
-       // ==============================================================================================================================
-       // Public member functions
-       // ==============================================================================================================================
-
-       public Scenario addScenario(Study aStudy, Scenario.Properties sprop)
-                       throws MissedPropertyException, InvalidPropertyException,
-                       MultiplyDefinedException, RuntimeException {
-               // -------------------------------------------------------
-               if (sprop.getManager() == null)
-                       sprop.setManager(aStudy.getAuthor());
-
-               Scenario scenario = new Scenario(sprop.setOwnerStudy(aStudy));
-               if (sprop.getBaseStep() != null)
-                       getScenarioService()
-                                       .copyContentsUpTo(scenario, sprop.getBaseStep());
-               Scenario previous = sprop.getInsertAfter();
-               Session session = Database.getSession();
-
-               if (previous == null) {
-                       aStudy.getScenariiList().add(scenario);
-               } else {
-                       aStudy.getScenariiList().add(
-                                       aStudy.getScenariiList().indexOf(previous) + 1, scenario);
-               }
-               session.update(this); // No need to update the Lucene index
-               session.save(scenario); // Must be done after updating this study because of the back reference to the study
-               if (sprop.getBaseStep() != null) {
-                       // No need to update the Knowledge Element index as Knowledge Elements are not copied
-                       scenario.refresh(); // Because saving the scenario changes the hashcode of copied Publications
-               }
-               KnowledgeElementType ucase = KnowledgeElement.selectType("usecase");
-               KnowledgeElement.Properties kprop = new KnowledgeElement.Properties();
-               User admin = UserDirectory.selectUser(1); // First user created when creating the database
-               kprop.setType(ucase).setTitle(aStudy.getTitle())
-                               .setValue(scenario.getTitle()).setAuthor(admin); // Internal Knowledge Element required by the validation process of
-                                                                                                                                       // knowledges
-               getScenarioService().addKnowledgeElement(scenario, kprop);
-               return scenario;
-       }
-
        /**
-        * @return
-        */
-       private ScenarioService getScenarioService() {
-               return _scenarioService;
-       }
-
-       public void setScenarioService(ScenarioService scenarioService) {
-               _scenarioService = scenarioService;
-       }
-
-       /**
-        * Promotes this study from In-Work to In-Draft then In-Check and APPROVED states. This function is called internally when promoting the
-        * final result document of the study.
+        * Promotes this study from In-Work to In-Draft then In-Check and APPROVED <BR>
+        * states. This function takes into account statuses of final result<BR>
+        * documents of the study.
         * 
-        * @return true if the demotion succeeded.
+        * @param aStudy
+        *            a study to promote
+        * @return true if the promotion succeeded.
         */
-       public boolean promote(Study aStudy) {
-               // ----------------------------
-               if (aStudy.getProgressState() == ProgressState.inWORK) {
+       @Transactional
+       public boolean promote(final Study aStudy) {
+               boolean res = true;
+               ValidationCycle cycle = getValidationCycleOf(aStudy,
+                               getStudyResultType(aStudy));
+
+               if (aStudy.getProgressState() == ProgressState.inWORK
+                               && cycle.enables(ValidationStep.REVIEW)
+                               && canBePromoted(aStudy)) {
                        aStudy.setProgressState(ProgressState.inDRAFT);
-               } else if (aStudy.getProgressState() == ProgressState.inDRAFT) {
+               } else if (((!cycle.enables(ValidationStep.REVIEW) && ((aStudy
+                               .getProgressState() == ProgressState.inWORK) || (aStudy
+                               .getProgressState() == ProgressState.inDRAFT))) || (cycle
+                               .enables(ValidationStep.REVIEW) && (aStudy.getProgressState() == ProgressState.inDRAFT)))
+                               && canBeReviewed(aStudy)) {
                        aStudy.setProgressState(ProgressState.inCHECK);
                        Revision myvers = new Revision(aStudy.getVersion());
                        if (myvers.isMinor()) {
                                aStudy.setVersion(myvers.incrementAs(aStudy.getProgressState())
                                                .toString());
                        }
-               } else if (aStudy.getProgressState() == ProgressState.inCHECK) {
+               } else if (aStudy.getProgressState() == ProgressState.inCHECK
+                               && canBeApproved(aStudy)) {
                        aStudy.setProgressState(ProgressState.APPROVED);
-               } else
-                       return false;
+                       updateKnowledgeElementsState(aStudy);
+               } else {
+                       res = false;
+               }
+               if (res) {
+                       res = update(aStudy);
+               }
 
-               return update(aStudy);
+               return res;
        }
 
        /**
-        * Moves this study from the Private to the Public area of the repository.
+        * Demotes this study from In-Check or In-Draft to In-Work states.
         * 
-        * @return true if the move succeeded.
-        * @see #isPublic()
+        * @param aStudy
+        *            a study to demote
+        * @return true if the demotion succeeded.
         */
-       public boolean moveToPublic(Study aStudy) {
-               // ------------------------------
-               if (aStudy.getVisibility() != Visibility.PRIVATE)
-                       return false;
+       @Transactional
+       public boolean demote(final Study aStudy) {
+               boolean res;
 
-               aStudy.setVisibility(Visibility.PUBLIC);
-               if (update(aStudy)) {
-                       return updateKnowledgeElementsIndex(aStudy); // If fails, the database roll-back is under responsibility of the caller
+               if (aStudy.getProgressState() == ProgressState.inCHECK
+                               || aStudy.getProgressState() == ProgressState.inDRAFT) {
+                       aStudy.setProgressState(ProgressState.inWORK);
+                       res = update(aStudy);
+               } else {
+                       res = false;
                }
-               return false;
+               return res;
        }
 
-       private boolean update(Study aStudy) {
-               try {
-                       Database.getSession().update(aStudy); // Update of relational base
-                       getIndex().update(aStudy); // Update of Lucene index
-                       return true;
-               } catch (Exception error) {
-                       logger.error("Unable to re-index the study '" + aStudy.getIndex()
-                                       + "', reason:", error);
-                       return false;
+       /**
+        * Moves this study from the Private to the Public area of the repository.
+        * 
+        * @param aStudy
+        *            a study to move
+        * @return true if the move succeeded.
+        * @see #isPublic()
+        */
+       @Transactional
+       public boolean moveToPublic(final Study aStudy) {
+               boolean isOk = false;
+               if (aStudy.getVisibility() == Visibility.PRIVATE) {
+                       aStudy.setVisibility(Visibility.PUBLIC);
+                       if (update(aStudy)) {
+                               isOk = updateKnowledgeElementsState(aStudy); // If fails, the database roll-back is under responsibility of the caller
+                       }
                }
+               return isOk;
        }
 
-       private boolean updateKnowledgeElementsIndex(Study aStudy) {
-               // ----------------------------------------------
-               try {
-                       IndexService lucin = getIndex();
-
-                       for (Iterator<Scenario> i = aStudy.getScenariiList().iterator(); i
-                                       .hasNext();) {
-                               Scenario scene = i.next();
-                               for (Iterator<KnowledgeElement> j = scene
-                                               .getAllKnowledgeElements().iterator(); j.hasNext();) {
-                                       KnowledgeElement kelm = j.next();
-                                       lucin.update(kelm);
-                               }
+       /**
+        * Moves this study from the Public to the Private area of the repository.
+        * 
+        * @param aStudy
+        *            a study to move
+        * @return true if the move succeeded.
+        */
+       @Transactional
+       public boolean moveToPrivate(final Study aStudy) {
+               boolean isOk = false;
+               if (aStudy.getVisibility() == Visibility.PUBLIC) {
+                       aStudy.setVisibility(Visibility.PRIVATE);
+                       if (update(aStudy)) {
+                               isOk = updateKnowledgeElementsState(aStudy); // If fails, the database roll-back is under responsibility of the caller
                        }
-                       return true;
-               } catch (Exception error) {
-                       logger.error("Unable to re-index Knowledge Elements, reason:",
-                                       error);
-                       return false;
                }
+               return isOk;
        }
 
        /**
-        * @return
+        * Update a study in the database.
+        * 
+        * @param aStudy
+        *            the study to update
+        * @return true if the study is updated successfully
         */
-       public IndexService getIndexService() {
-               return _indexService;
-       }
-
-       public void setIndexService(IndexService indexService) {
-               _indexService = indexService;
+       private boolean update(final Study aStudy) {
+               boolean isOk = false;
+               try {
+                       getStudyDAO().merge(aStudy); // Update of relational base
+                       setShortCuts(aStudy); // RKV: initialize transient actors set
+                       // RKV: getIndex().update(aStudy); // Update of Lucene index
+                       isOk = true;
+               } catch (Exception e) {
+                       LOG.error("STD-000001", e, aStudy.getIndex(), e.getMessage());
+               }
+               return isOk;
        }
 
        /**
-        * Get project settings.
+        * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
         * 
-        * @return Project settings service
+        * @param aStudy
+        *            the study
+        * @return true if reference building is succeded
         */
-       private ProjectSettingsService getProjectSettings() {
-               return _projectSettingsService;
+       @Transactional
+       private boolean buildReference(final Study aStudy) {
+               String pattern = aStudy.getReference(); // The study being supposed just created, its reference is the reference pattern
+               IDBuilder tool = selectIDBuilder(aStudy.getDate());
+               if (tool == null) {
+                       tool = new IDBuilder(aStudy.getDate());
+                       getIDBuilderDAO().create(tool);
+               }
+               aStudy.setReference(buildReference(tool, pattern, aStudy));
+               return true;
        }
 
        /**
-        * Set project settings service.
+        * Build reference for the study. The reference of the study is stored as a new reference pattern (IDBuilder).
         * 
-        * @param projectSettingsService
-        *            project settings service
+        * @param aBuilder
+        *            the id builder
+        * @param study
+        *            the study
+        * @param pattern
+        *            the reference pattern
+        * @return true if reference building is succeded
         */
-       public void setProjectSettings(ProjectSettingsService projectSettingsService) {
-               _projectSettingsService = projectSettingsService;
+       @Transactional
+       public String buildReference(final IDBuilder aBuilder,
+                       final String pattern, final Study study) {
+               char[] format = pattern.toCharArray();
+               char[] ref = new char[80]; // Better evaluate the length of the generated string
+               int next = aBuilder.getBase() + 1;
+
+               int count = 0;
+               for (int i = 0; i < format.length; i++) {
+
+                       // Insertion of attribute values
+                       if (format[i] == '%') {
+                               i += 1;
+
+                               if (format[i] == 'y') { // Insertion of year in format 2 (e.g. 09) or 4 (e.g. 2009) digits
+                                       int n = i;
+                                       while (format[i] == 'y') {
+                                               i += 1;
+                                               if (i == format.length) {
+                                                       break;
+                                               }
+                                       }
+                                       SimpleDateFormat tostring = new SimpleDateFormat("yyyy"); // RKV: NOPMD: TODO: Use locale here?
+                                       String year = tostring.format(study.getDate());
+                                       year = year.substring(4 - (i - n), 4); // 4-(i-n) must be equal to either 0 or 2
+                                       for (int j = 0; j < year.length(); j++) {
+                                               ref[count] = year.charAt(j);
+                                               count += 1;
+                                       }
+                                       i -= 1; // Back to the last 'y' character
+                               } else if (format[i] == '0') { // Insertion of the index
+                                       int n = i;
+                                       while (format[i] == '0') {
+                                               i += 1;
+                                               if (i == format.length) {
+                                                       break;
+                                               }
+                                       }
+                                       DecimalFormat tostring = new DecimalFormat(pattern
+                                                       .substring(n, i));
+                                       String number = tostring.format(next);
+                                       for (int j = 0; j < number.length(); j++) {
+                                               ref[count] = number.charAt(j);
+                                               count += 1;
+                                       }
+                                       i -= 1; // Back to the last '0' character
+                               }
+                               // Keep the character
+                       } else {
+                               ref[count] = format[i];
+                               count += 1;
+                       }
+               }
+               // Incrementation of the number of study
+               aBuilder.setBase(next);
+               getIDBuilderDAO().update(aBuilder);
+               return String.copyValueOf(ref, 0, count);
        }
 
        /**
-        * Get the projectElementService.
+        * Find an id builder by date.
         * 
-        * @return the projectElementService
+        * @param date
+        *            the date
+        * @return found id builder
         */
-       public ProjectElementService getProjectElementService() {
-               return _projectElementService;
+       private IDBuilder selectIDBuilder(final Date date) {
+               Calendar aDate = Calendar.getInstance();
+               aDate.setTime(date);
+               return getIDBuilderDAO().findByCriteria(
+                               Restrictions.eq("cycle", aDate.get(Calendar.YEAR)));
        }
 
        /**
-        * Set the projectElementService.
+        * Fill transient collection ModifiableActors of the study.
         * 
-        * @param projectElementService
-        *            the projectElementService to set
+        * @param aStudy
+        *            the study
         */
-       public void setProjectElementService(
-                       ProjectElementService projectElementService) {
+       private void resetActorsShortCut(final Study aStudy) {
+               getModifiableActors(aStudy).clear();
+               // Get all actors involved in validation cycles
+               for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
+                               .values().iterator(); i.hasNext();) {
+                       ValidationCycle cycle = i.next();
+                       User[] user = cycle.getAllActors();
+                       for (int j = 0; j < user.length; j++) {
+                               getModifiableActors(aStudy).add(user[j]);
+                       }
+               }
+               // Get all other actors
+               for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
+                               .hasNext();) {
+                       Relation link = i.next();
+                       Class<?> kindof = link.getClass().getSuperclass();
+                       if (!kindof.equals(ActorRelation.class)) {
+                               continue;
+                       }
+                       getModifiableActors(aStudy).add(((ActorRelation) link).getTo());
+               }
+       }
+
+       /**
+        * Update knowledge elements states.
+        * 
+        * @param aStudy
+        *            the study
+        * @return true if succeeded
+        */
+       private boolean updateKnowledgeElementsState(final Study aStudy) {
+               for (Scenario scenario : aStudy.getScenariiList()) {
+                       for (KnowledgeElement element : scenario.getAllKnowledgeElements()) {
+                               element.setProgressState(aStudy.getProgressState());
+                       }
+               }
+               return true;
+       }
+
+       /**
+        * Get lucene index service. Create a lucene index if it does not exist.
+        * 
+        * @return index service
+        * @throws IOException
+        *             if error occurs during lucene index creation
+        */
+       private IndexService getIndex() throws IOException {
+               IndexService lucin = getIndexService();
+               if (IndexWriter.isLocked(FSDirectory.open(getRepositoryService()
+                               .getRepositoryIndexDirectory()))) {
+                       IndexWriter.unlock(FSDirectory.open(getRepositoryService()
+                                       .getRepositoryIndexDirectory()));
+               }
+               if (!lucin.exists()) {
+                       lucin.create(); // Happens when re-indexing all studies
+               }
+               return lucin;
+       }
+
+       /**
+        * Create a new validation cycle for documents of the given study.
+        * 
+        * @param from
+        *            the study
+        * @param cycle
+        *            the cycle description
+        * @return the new validation cycle
+        */
+       protected ValidationCycle createValidationCycle(
+                       final Study from,
+                       final ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle) {
+               Actor[] actype = cycle.getActorTypes();
+               User.Properties uprop = new User.Properties();
+
+               ValidationCycle aValidationCycle = new ValidationCycle();
+               aValidationCycle.setDocumentType(getDocumentTypeService().selectType(
+                               cycle.getName())); // Null in case of default validation cycle
+               // context = new ValidationCycleRelation(from, vprop);
+               // RKV aValidationCycle.context = null; // Validation cycle defined in the workflow
+               for (int i = 0; i < actype.length; i++) {
+                       User actor = null;
+                       if (actype[i] != null) {
+                               try {
+                                       if (actype[i] == Actor.manager) {
+                                               actor = from.getAuthor();
+                                       } else if (actype[i] == Actor.Nx1) {
+                                               List<User> manager = getUserService().selectUsersWhere(
+                                                               uprop.setOrganizationName("Nx1"));
+                                               if (manager.size() == 1) {
+                                                       actor = manager.get(0);
+                                               }
+                                       } else if (actype[i] == Actor.Nx2) {
+                                               List<User> manager = getUserService().selectUsersWhere(
+                                                               uprop.setOrganizationName("Nx2"));
+                                               if (manager.size() == 1) {
+                                                       actor = manager.get(0);
+                                               }
+                                       } else { /* Actor.customer */
+                                               actor = from.getAuthor();
+                                               // TODO: Get the customer of the study, if exists
+                                       }
+                               } catch (Exception e) { // Should not happen
+                                       actor = null;
+                               }
+                       }
+                       if (i == 0) {
+                               aValidationCycle.setReviewer(actor);
+                       } else if (i == 1) {
+                               aValidationCycle.setApprover(actor);
+                       } else if (i == 2) {
+                               aValidationCycle.setSignatory(actor);
+                       }
+               }
+               return aValidationCycle;
+       }
+
+       /**
+        * Remove a validation step from the validation cycle.
+        * 
+        * @param aValidationCycle
+        *            the validation cycle
+        * @param step
+        *            the validation step to remove
+        */
+       @Transactional
+       protected void remove(final ValidationCycle aValidationCycle,
+                       final ValidationStep step) {
+               if (step == ValidationStep.REVIEW) {
+                       aValidationCycle.setReviewer(null);
+               } else if (step == ValidationStep.APPROVAL) {
+                       aValidationCycle.setApprover(null);
+               } else if (step == ValidationStep.ACCEPTANCE
+                               || step == ValidationStep.REFUSAL) {
+                       aValidationCycle.setSignatory(null);
+               }
+               if (aValidationCycle.isSaved()) {
+                       getValidationCycleDAO().update(aValidationCycle);
+               }
+       }
+
+       /**
+        * Reset actors for the validation cycle.
+        * 
+        * @param aValidationCycle
+        *            the validation cycle to update
+        * @param vprop
+        *            new validation cycle properties containing new actors
+        */
+       @Transactional
+       public void resetActors(final ValidationCycle aValidationCycle,
+                       final ValidationCycle.Properties vprop) {
+               aValidationCycle.setPublisher(vprop.getPublisher()); // May be null
+               aValidationCycle.setReviewer(vprop.getReviewer()); // May be null
+               aValidationCycle.setApprover(vprop.getApprover()); // May be null
+               aValidationCycle.setSignatory(vprop.getSignatory()); // May be null
+               if (aValidationCycle.isSaved()) {
+                       getValidationCycleDAO().merge(aValidationCycle);
+               }
+       }
+
+       /**
+        * Set actor for the given validation cycle and validation step.
+        * 
+        * @param aValidationCycle
+        *            the validation cycle
+        * @param step
+        *            the validation step
+        * @param actor
+        *            the actor to set
+        */
+       @Transactional
+       protected void setActor(final ValidationCycle aValidationCycle,
+                       final ValidationStep step, final User actor) {
+               if (step == ValidationStep.PROMOTION) {
+                       aValidationCycle.setPublisher(actor);
+               } else if (step == ValidationStep.REVIEW) {
+                       aValidationCycle.setReviewer(actor);
+               } else if (step == ValidationStep.APPROVAL) {
+                       aValidationCycle.setApprover(actor);
+               } else if (step == ValidationStep.ACCEPTANCE
+                               || step == ValidationStep.REFUSAL) {
+                       aValidationCycle.setSignatory(actor);
+               }
+               if (aValidationCycle.isSaved()) {
+                       getValidationCycleDAO().update(aValidationCycle);
+               }
+       }
+
+       /**
+        * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
+        * 
+        * @param aStudy
+        *            the study
+        * @return the actors of this study
+        * @see #hasActor(User)
+        */
+       public Set<User> getActors(final Study aStudy) {
+               if (aStudy.getActor() == null) {
+                       setShortCuts(aStudy);
+               }
+               return Collections.unmodifiableSet(aStudy.getActor());
+       }
+
+       /**
+        * Returns all actors of this study other than the author, including contributors, reviewers and approvers.
+        * 
+        * @param aStudy
+        *            the study
+        * @return the modifiable set of actors of this study
+        * @see #hasActor(User)
+        */
+       public Set<User> getModifiableActors(final Study aStudy) {
+               if (aStudy.getActor() == null) {
+                       setShortCuts(aStudy);
+               }
+               return aStudy.getActor();
+       }
+
+       /**
+        * Returns unmodifiable initialized transient list of contributors of this study.
+        * 
+        * @param aStudy
+        *            the study
+        * @return the unmodifiable not null transient list of contributors of this study
+        */
+       public List<User> getContributors(final Study aStudy) {
+               if (aStudy.getContributor() == null) {
+                       setShortCuts(aStudy);
+               }
+               return Collections.unmodifiableList(aStudy.getContributor()); // May be empty
+       }
+
+       /**
+        * Returns modifiable initialized transient list of contributors of this study.
+        * 
+        * @param aStudy
+        *            the study
+        * @return the modifiable not null transient list of contributors of this study
+        */
+       public List<User> getModifiableContributors(final Study aStudy) {
+               if (aStudy.getContributor() == null) {
+                       setShortCuts(aStudy);
+               }
+               return aStudy.getContributor(); // May be empty
+       }
+
+       /**
+        * Returns the validation cycle of the given document type.
+        * 
+        * @param aStudy
+        *            the study
+        * @param type
+        *            the document type being subject of validation
+        * @return the validation cycle of the document, or null if not defined.
+        */
+       public ValidationCycle getValidationCycleOf(final Study aStudy,
+                       final DocumentType type) {
+               ValidationCycle result = null;
+               if (aStudy != null) {
+                       if (aStudy.getValidationCycles() == null
+                                       || aStudy.getValidationCycles().isEmpty()) {
+                               setShortCuts(aStudy);
+                       }
+                       if (type != null) {
+                               result = aStudy.getValidationCycles().get(type.getName());
+                       }
+               }
+               if ((result == null) && (aStudy != null)) {
+                       if ((type == null) || type.isStepResult()) {
+                               result = aStudy.getValidationCycles().get("default"); // "default" validation cycle defined in the configuration, if exist
+                       }
+                       if (result == null) {
+                               result = aStudy.getValidationCycles().get("built-in");
+                       }
+               }
+               return result;
+       }
+
+       /**
+        * Checks if the given user is actor of this study. Actors include contributors, reviewers and approvers.
+        * 
+        * @param aStudy
+        *            the study
+        * @param user
+        *            the user to look for
+        * @return true if the given user is actor of this study.
+        * @see #getActors()
+        */
+       public boolean hasActor(final Study aStudy, final User user) {
+               if (user == null) {
+                       return false;
+               }
+               for (Iterator<User> i = getActors(aStudy).iterator(); i.hasNext();) {
+                       User involved = i.next();
+                       if (involved.equals(user)) {
+                               return true;
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * Checks if the given user participates to this study. The Study staff includes the author and contributors.
+        * 
+        * @param aStudy
+        *            the study
+        * @param user
+        *            the user to look for
+        * @return true if the given user is actor of this study.
+        * @see #getContributors()
+        */
+       public boolean isStaffedBy(final Study aStudy, final User user) {
+               if (user == null) {
+                       return false;
+               }
+               if (aStudy == null) {
+                       return false;
+               }
+               if (aStudy.getAuthor() == null) {
+                       return false;
+               }
+               if (aStudy.getAuthor().equals(user)) {
+                       return true;
+               }
+               for (Iterator<User> i = getContributors(aStudy).iterator(); i.hasNext();) {
+                       if (i.next().equals(user)) {
+                               return true;
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * Initialize shortcuts of the study as its transient collections.
+        * 
+        * @param aStudy
+        *            the study
+        */
+       public void loadWorkflow(final Study aStudy) {
+               setShortCuts(aStudy);
+       }
+
+       /**
+        * Initialize shortcuts of the study as its transient collections.
+        * 
+        * @param aStudy
+        *            the study
+        */
+       public void setShortCuts(final Study aStudy) {
+               aStudy.getContributor().clear();
+               aStudy.getValidationCycles().clear();
+               aStudy.getActor().clear();
+
+               // Get the contributors
+               for (Iterator<Relation> i = aStudy.getRelations(
+                               ContributorRelation.class).iterator(); i.hasNext();) {
+                       ContributorRelation link = (ContributorRelation) i.next();
+                       aStudy.getContributor().add(link.getTo());
+               }
+               // Get the validation cycles specific to this study
+               for (Iterator<Relation> i = aStudy.getRelations(
+                               ValidationCycleRelation.class).iterator(); i.hasNext();) {
+                       ValidationCycleRelation link = (ValidationCycleRelation) i.next();
+                       aStudy.getValidationCycles().put(link.getDocumentType().getName(),
+                                       link.getTo()); // The associated document type is necessarily not null in this
+                       // context
+               }
+               // Get the validation cycles coming from the configured workflow and not overridden in this study
+               for (Iterator<ProjectSettingsServiceImpl.ProjectSettingsValidationCycle> i = getProjectSettings()
+                               .getAllValidationCycles().iterator(); i.hasNext();) {
+                       ProjectSettingsServiceImpl.ProjectSettingsValidationCycle cycle = i
+                                       .next();
+                       String type = cycle.getName();
+                       if (!aStudy.getValidationCycles().containsKey(type)) {
+                               aStudy.getValidationCycles().put(type,
+                                               createValidationCycle(aStudy, cycle));
+                       }
+               }
+               // Get all corresponding actors
+               for (Iterator<ValidationCycle> i = aStudy.getValidationCycles()
+                               .values().iterator(); i.hasNext();) {
+                       ValidationCycle cycle = i.next();
+                       User[] user = cycle.getAllActors();
+                       for (int j = 0; j < user.length; j++) {
+                               aStudy.getActor().add(user[j]);
+                       }
+               }
+               // Get all other actors
+               for (Iterator<Relation> i = aStudy.getAllRelations().iterator(); i
+                               .hasNext();) {
+                       Relation link = i.next();
+                       Class<?> kindof = link.getClass().getSuperclass();
+                       if (!kindof.equals(ActorRelation.class)) {
+                               continue;
+                       }
+                       aStudy.getActor().add(((ActorRelation) link).getTo());
+               }
+       }
+
+       /**
+        * 
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#markStudyAsReference(org.splat.dal.bo.som.Study)
+        */
+       @Transactional
+       public boolean markStudyAsReference(final Study aStudy) {
+               boolean res = false;
+               if (aStudy.getProgressState() == ProgressState.APPROVED) {
+                       aStudy.setMarkreference(1);
+                       aStudy.setProgressState(ProgressState.TEMPLATE);
+                       res = updateKnowledgeElementsState(aStudy);
+                       getStudyDAO().merge(aStudy);
+               }
+               return res;
+       }
+
+       /**
+        * 
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#removeStudyAsReference(org.splat.dal.bo.som.Study)
+        */
+       @Transactional
+       public void removeStudyAsReference(final Study aStudy) {
+               aStudy.setMarkreference(0);
+               aStudy.setProgressState(ProgressState.APPROVED);
+               updateKnowledgeElementsState(aStudy);
+               getStudyDAO().merge(aStudy);
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#getDescription(java.lang.Long)
+        */
+       @Override
+       @Transactional(readOnly = true)
+       public String getDescription(final Long studyId)
+                       throws InvalidParameterException {
+               if (studyId == null) {
+                       throw new InvalidParameterException(PARAM_STUDY_ID, "null");
+               }
+               Study study = _studyDAO.get(studyId);
+               if (study == null) {
+                       throw new InvalidParameterException(PARAM_STUDY_ID, studyId
+                                       .toString());
+               }
+               return study.getDescription();
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#setDescription(java.lang.Long, java.lang.String)
+        */
+       @Transactional
+       public void setDescription(final Long studyId, final String descriptionText)
+                       throws InvalidParameterException {
+               if (studyId == null) {
+                       throw new InvalidParameterException(PARAM_STUDY_ID, "null");
+               }
+               Study study = _studyDAO.get(studyId);
+               if (study == null) {
+                       throw new InvalidParameterException(PARAM_STUDY_ID, studyId
+                                       .toString());
+               }
+               study.setAttribute(new DescriptionAttribute(study, descriptionText));
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#removeStudyDescription(java.lang.Long)
+        */
+       @Transactional
+       public boolean removeDescription(final Long studyId)
+                       throws InvalidParameterException {
+               if (studyId == null) {
+                       throw new InvalidParameterException(PARAM_STUDY_ID, String
+                                       .valueOf(studyId));
+               }
+               Study study = _studyDAO.get(studyId);
+               if (study == null) {
+                       throw new InvalidParameterException(PARAM_STUDY_ID, String
+                                       .valueOf(studyId));
+               }
+               return study.removeAttribute(study
+                               .getAttribute(DescriptionAttribute.class));
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#getReaders(long)
+        */
+       @Transactional(readOnly = true)
+       public List<UserDTO> getReaders(final long studyId)
+                       throws InvalidParameterException {
+               Study aStudy = selectStudy(studyId);
+               if (aStudy == null) {
+                       throw new InvalidParameterException(PARAM_STUDY_ID, String
+                                       .valueOf(studyId));
+               }
+               List<Relation> relations = aStudy.getRelations(ReaderRelation.class);
+               List<UserDTO> result = new ArrayList<UserDTO>();
+               for (Relation relation : relations) {
+                       result.add(BeanHelper.copyBean(relation.getTo(), UserDTO.class));
+               }
+               return Collections.unmodifiableList(result);
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#addReader(long, long)
+        */
+       @Transactional
+       public boolean addReader(final long studyId, final long userId)
+                       throws InvalidParameterException {
+               Study aStudy = selectStudy(studyId);
+               if (aStudy == null) {
+                       throw new InvalidParameterException(PARAM_STUDY_ID, String
+                                       .valueOf(studyId));
+               }
+               User user = _userService.selectUser(userId);
+               if (user == null) {
+                       throw new InvalidParameterException("userId", String
+                                       .valueOf(userId));
+               }
+
+               for (Relation relation : aStudy.getRelations(ReaderRelation.class)) {
+                       if (user.equals(relation.getTo())) {
+                               return false;
+                       }
+               }
+               aStudy.addRelation(new ReaderRelation(aStudy, user));
+               update(aStudy);
+               return true;
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#removeReader(long, long)
+        */
+       @Transactional
+       public boolean removeReader(final long studyId, final long userId)
+                       throws InvalidParameterException {
+               Study aStudy = selectStudy(studyId);
+               if (aStudy == null) {
+                       throw new InvalidParameterException(PARAM_STUDY_ID, String
+                                       .valueOf(studyId));
+               }
+               User user = _userService.selectUser(userId);
+               if (user == null) {
+                       throw new InvalidParameterException("userId", String
+                                       .valueOf(userId));
+               }
+
+               Relation relation = aStudy.removeRelation(ReaderRelation.class, user);
+               update(aStudy);
+               return relation != null;
+       }
+
+       /**
+        * Get project settings.
+        * 
+        * @return Project settings service
+        */
+       private ProjectSettingsService getProjectSettings() {
+               return _projectSettings;
+       }
+
+       /**
+        * Set project settings service.
+        * 
+        * @param projectSettingsService
+        *            project settings service
+        */
+       public void setProjectSettings(
+                       final ProjectSettingsService projectSettingsService) {
+               _projectSettings = projectSettingsService;
+       }
+
+       /**
+        * Get the projectElementService.
+        * 
+        * @return the projectElementService
+        */
+       public ProjectElementService getProjectElementService() {
+               return _projectElementService;
+       }
+
+       /**
+        * Set the projectElementService.
+        * 
+        * @param projectElementService
+        *            the projectElementService to set
+        */
+       public void setProjectElementService(
+                       final ProjectElementService projectElementService) {
                _projectElementService = projectElementService;
        }
+
+       /**
+        * 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;
+       }
+
+       /**
+        * Get the indexService.
+        * 
+        * @return the indexService
+        */
+       public IndexService getIndexService() {
+               return _indexService;
+       }
+
+       /**
+        * Set the indexService.
+        * 
+        * @param indexService
+        *            the indexService to set
+        */
+       public void setIndexService(final IndexService indexService) {
+               _indexService = indexService;
+       }
+
+       /**
+        * 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 iDBuilderDAO.
+        * 
+        * @return the iDBuilderDAO
+        */
+       public IDBuilderDAO getIDBuilderDAO() {
+               return _iDBuilderDAO;
+       }
+
+       /**
+        * Set the iDBuilderDAO.
+        * 
+        * @param builderDAO
+        *            the iDBuilderDAO to set
+        */
+       public void setIDBuilderDAO(final IDBuilderDAO builderDAO) {
+               _iDBuilderDAO = builderDAO;
+       }
+
+       /**
+        * Get the scenarioDAO.
+        * 
+        * @return the scenarioDAO
+        */
+       public ScenarioDAO getScenarioDAO() {
+               return _scenarioDAO;
+       }
+
+       /**
+        * Set the scenarioDAO.
+        * 
+        * @param scenarioDAO
+        *            the scenarioDAO to set
+        */
+       public void setScenarioDAO(final ScenarioDAO scenarioDAO) {
+               _scenarioDAO = scenarioDAO;
+       }
+
+       /**
+        * Get the validationCycleDAO.
+        * 
+        * @return the validationCycleDAO
+        */
+       public ValidationCycleDAO getValidationCycleDAO() {
+               return _validationCycleDAO;
+       }
+
+       /**
+        * Set the validationCycleDAO.
+        * 
+        * @param validationCycleDAO
+        *            the validationCycleDAO to set
+        */
+       public void setValidationCycleDAO(
+                       final ValidationCycleDAO validationCycleDAO) {
+               _validationCycleDAO = validationCycleDAO;
+       }
+
+       /**
+        * 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;
+       }
+
+       /**
+        * Get the userService.
+        * 
+        * @return the userService
+        */
+       public UserService getUserService() {
+               return _userService;
+       }
+
+       /**
+        * Set the userService.
+        * 
+        * @param userService
+        *            the userService to set
+        */
+       public void setUserService(final UserService userService) {
+               _userService = userService;
+       }
+
+       /**
+        * Get the publicationDAO.
+        * 
+        * @return the publicationDAO
+        */
+       public PublicationDAO getPublicationDAO() {
+               return _publicationDAO;
+       }
+
+       /**
+        * Set the publicationDAO.
+        * 
+        * @param publicationDAO
+        *            the publicationDAO to set
+        */
+       public void setPublicationDAO(final PublicationDAO publicationDAO) {
+               _publicationDAO = publicationDAO;
+       }
+
+       /**
+        * 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 documentDAO.
+        * 
+        * @return the documentDAO
+        */
+       public DocumentDAO getDocumentDAO() {
+               return _documentDAO;
+       }
+
+       /**
+        * Set the documentDAO.
+        * 
+        * @param documentDAO
+        *            the documentDAO to set
+        */
+       public void setDocumentDAO(final DocumentDAO documentDAO) {
+               _documentDAO = documentDAO;
+       }
+
+       /**
+        * Get the descriptionAttributeDAO.
+        * 
+        * @return the descriptionAttributeDAO
+        */
+       public DescriptionAttributeDAO getDescriptionAttributeDAO() {
+               return _descriptionAttributeDAO;
+       }
+
+       /**
+        * Set the descriptionAttributeDAO.
+        * 
+        * @param descriptionAttributeDAO
+        *            the descriptionAttributeDAO to set
+        */
+       public void setDescriptionAttributeDAO(
+                       final DescriptionAttributeDAO descriptionAttributeDAO) {
+               _descriptionAttributeDAO = descriptionAttributeDAO;
+       }
+
+       /**
+        * Get the usedByRelationDAO.
+        * 
+        * @return the usedByRelationDAO
+        */
+       public UsedByRelationDAO getUsedByRelationDAO() {
+               return _usedByRelationDAO;
+       }
+
+       /**
+        * Set the usedByRelationDAO.
+        * 
+        * @param usedByRelationDAO
+        *            the usedByRelationDAO to set
+        */
+       public void setUsedByRelationDAO(final UsedByRelationDAO usedByRelationDAO) {
+               _usedByRelationDAO = usedByRelationDAO;
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#getStudyResultType(org.splat.dal.bo.som.Study)
+        */
+       @Override
+       @Transactional(readOnly = true)
+       public DocumentType getStudyResultType(final Study study) {
+               DetachedCriteria query = DetachedCriteria.forClass(DocumentType.class)
+                               .addOrder(Order.desc("result"));
+               return getDocumentTypeDAO().getFirstResult(query);
+       }
+
+       /**
+        * Get the documentTypeDAO.
+        * 
+        * @return the documentTypeDAO
+        */
+       public DocumentTypeDAO getDocumentTypeDAO() {
+               return _documentTypeDAO;
+       }
+
+       /**
+        * Set the documentTypeDAO.
+        * 
+        * @param documentTypeDAO
+        *            the documentTypeDAO to set
+        */
+       public void setDocumentTypeDAO(final DocumentTypeDAO documentTypeDAO) {
+               _documentTypeDAO = documentTypeDAO;
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#canBeApproved(org.splat.dal.bo.som.Study)
+        */
+       @Override
+       @Transactional(readOnly = true)
+       public boolean canBeApproved(final Study study) {
+               return resultDocsAtLeast(study, ProgressState.APPROVED);
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#canBePromoted(org.splat.dal.bo.som.Study)
+        */
+       @Override
+       @Transactional(readOnly = true)
+       public boolean canBePromoted(final Study study) {
+               boolean res;
+               if (study.getProgressState().compareTo(ProgressState.inDRAFT) < 0) {
+                       res = resultDocsAtLeast(study, ProgressState.inDRAFT);
+               } else {
+                       res = canBeReviewed(study);
+               }
+               return res;
+       }
+
+       /**
+        * {@inheritDoc}
+        * 
+        * @see org.splat.service.StudyService#canBeReviewed(org.splat.dal.bo.som.Study)
+        */
+       @Override
+       @Transactional(readOnly = true)
+       public boolean canBeReviewed(final Study study) {
+               return resultDocsAtLeast(study, ProgressState.inCHECK);
+       }
+
+       /**
+        * Check that all result documents of the study are at least in the given state.
+        * 
+        * @param study
+        *            the study to check
+        * @param state
+        *            the minimal acceptable state
+        * @return true if study result documents have acceptable states
+        */
+       private boolean resultDocsAtLeast(final Study study,
+                       final ProgressState state) {
+               boolean res = true;
+               // Check that all study result documents have the state APPROVED or more.
+               for (Publication pub : getProjectElementService().getLastStep(study)
+                               .getResultDocuments()) {
+                       res = pub.getProgressState().compareTo(state) >= 0;
+                       if (!res) {
+                               break;
+                       }
+               }
+               return res;
+       }
 }