Salome HOME
More business logic has been moved from BO to services. ServiceLocator is created...
[tools/siman.git] / Workspace / Siman / src / org / splat / simer / OpenStudy.java
index 42247c11943b68480b8165220e28c297279efd5c..dd9937e34ec299c5d64a047d9e67e8cc1c27632b 100644 (file)
@@ -1,4 +1,5 @@
 package org.splat.simer;
+
 /**
  * 
  * @author    Daniel Brunier-Coulin
@@ -26,9 +27,9 @@ import org.splat.dal.bo.som.Document;
 import org.splat.dal.bo.som.DocumentType;
 import org.splat.dal.bo.som.KnowledgeElement;
 import org.splat.dal.bo.som.ProgressState;
-import org.splat.service.ProjectElementService;
-import org.splat.service.ScenarioService;
+import org.splat.service.DocumentTypeService;
 import org.splat.service.StepService;
+import org.splat.service.StudyService;
 import org.splat.service.technical.RepositoryService;
 import org.splat.dal.bo.som.Publication;
 import org.splat.som.Revision;
@@ -38,32 +39,22 @@ import org.splat.som.Step;
 import org.splat.som.StepRights;
 import org.splat.dal.bo.som.Study;
 import org.splat.som.StudyRights;
-import org.splat.wapp.Menu;
 import org.splat.wapp.ToolBar;
 
-
 public class OpenStudy extends OpenObject implements OpenStudyServices {
 
        /**
         * Serial version ID.
         */
-       protected final static Logger   logger = org.splat.simer.Action.logger;
-    
-    private  Study       mystudy;
-    private  StudyRights urightstudy;              // User rights on the open study
-       private  StepRights  urightstep;               // User rights on the selected step
-    private  String      version;
-    private  String      credate;
-    private  String      lasdate;
-    private  Publication selecdoc;
-       /**
-        * Injected project element service.
-        */
-       private ProjectElementService _projectElementService;
-       /**
-        * Injected scenario service.
-        */
-       private ScenarioService _scenarioService;
+       protected final static Logger logger = org.splat.simer.Action.logger;
+
+       private Study mystudy;
+       private StudyRights urightstudy; // User rights on the open study
+       private StepRights urightstep; // User rights on the selected step
+       private String version;
+       private String credate;
+       private String lasdate;
+       private Publication selecdoc;
        /**
         * Injected step service.
         */
@@ -72,418 +63,450 @@ public class OpenStudy extends OpenObject implements OpenStudyServices {
         * Injected repository service.
         */
        private RepositoryService _repositoryService;
-//  ==============================================================================================================================
-//  Constructor
-//  ==============================================================================================================================
-
-    /**
-     * Open the given study in the current http session.
-     * @param user the current user
-     * @param study the study to open
-     * @return this open study object
-     */
-    public OpenStudy open (User user, Study study) {
-//  -----------------------------------------
-      ResourceBundle    custom    = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
-      SimpleDateFormat  datstring = new SimpleDateFormat(custom.getString("date.format"));
-      Revision.Format   verstring = new Revision.Format(getProjectSettings().getRevisionPattern());
-        
-      cuser       = user;                           // May be null if nobody connected
-      mystudy     = study;
-      selection   = "0.1";                          // Default selection
-      selecdoc    = null;
-
-//    Preparation of the display
-      version     = verstring.format(mystudy.getVersion());
-      credate     = datstring.format(mystudy.getDate());
-      lasdate     = "";                             // Not yet supported
-      description = mystudy.getDescription();
-      involving   = new ArrayList<Step>(1);
-      context     = new ArrayList<SimulationContextFacade>();
-      ustep       = getProjectElementService().getFirstStep(mystudy);
-      ustep.setActor(cuser);
-      involving.add(ustep);
-      for (Iterator<SimulationContext> i=ustep.getAllSimulationContexts().iterator(); i.hasNext(); ) {
-        context.add( new SimulationContextFacade(i.next(), getProjectSettings().getAllSteps()) );
-      }
-      if (mystudy.isStaffedBy(cuser) || mystudy.hasActor(cuser)) {
-//     ProgressState state = mystudy.getProgressState();
-//         if           (state == ProgressState.inCHECK)  popup = ApplicationSettings.getPopupMenu("stapprovable");
-//         else if      (state == ProgressState.APPROVED) popup = ApplicationSettings.getPopupMenu("stapproved");
-/*      else         */                                popup = ApplicationSettings.getPopupMenu("steditable");
-           popup.setContext("study", new StudyRights(cuser, mystudy));
-      }
-      urightstudy = new StudyRights(cuser, mystudy);
-      urightstep  = new StepRights(cuser, ustep);
-
-//RKV      menu = new StudyMenu(mystudy);
-      menu = ((StudyMenu)getMenu()).init(mystudy); //RKV
-      menu.selects(selection);                      // Initializes menu items to be displayed
-      setupContents();                              // Initializes documents and knowledge at ustep
-      return this;
-    }
-
-//  ==============================================================================================================================
-//  Getters
-//  ==============================================================================================================================
-
-       public String getAuthorName() {
-//  -----------------------------
-      return mystudy.getAuthor().toString();
-    }
-    public Long getIndex() {
-//  -------------------------
-      return mystudy.getIndex();
-    }
-    public String getDate () {
-//  ------------------------
-      return credate;
-    }
-    public StudyMenu getMenu () {
-//  ---------------------------
-      return (StudyMenu)menu;
-    }
-    public ProgressState getProgressState() {
-//  ----------------------------------------
-      return mystudy.getProgressState();
-    }
-    public String getLastModificationDate () {
-//  ----------------------------------------
-      return lasdate;
-    }
-    public ToolBar getModuleBar () {
-//  ------------------------------
-      return ApplicationSettings.getMe().getModuleBar(getSelectedStep());
-    }
-    public String getReference() {
-//  ----------------------------
-      return mystudy.getReference();
-    }
-    public Publication getSelectedDocument () {
-//  -----------------------------------------
-      return selecdoc;
-    }
-    public StepRights getSelectedStepRights () {
-//  ------------------------------------------
-      return urightstep;
-    }
-    public StudyRights getStudyRights () {
-//  ------------------------------------
-      return urightstudy;
-    }
-    public Study getStudyObject () {
-//  ------------------------------
-      return mystudy;
-    }
-    public String getTitle() {
-//  ------------------------
-      return mystudy.getTitle();
-    }
-    public String getType () {
-//  ------------------------
-      return ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale()).getString("label.study");
-    }
-    public String getVersion () {
-//  ---------------------------
-      return version;
-    }
-    public boolean isStepEnabled () {
-//  -------------------------------
-      return urightstep.isEnabled();
-    }
-
-//  ==============================================================================================================================
-//  Public services
-//  ==============================================================================================================================
-
-    public URL newTemplateBasedDocument (String typename, User author) {
-//  ------------------------------------------------------------------
-      String filename = typename + ".xml";     // Only XML templates are writeable
-      File   template = new File(getRepositoryService().getTemplatePath() + filename);      
-      if   (!template.exists()) return null;
-      
-      Session      connex  = Database.getSession();
-         Transaction  transax = connex.beginTransaction();
-      try {
-        File  udir   = getRepositoryService().getDownloadDirectory(author);
-        File  credoc = new File(udir.getPath() + "/" + filename);
-
-//      Creation of the meta-document
-        Step                step  = getSelectedStep();   // Should we check if the given document type is compatible ?
-           DocumentType        type  = Document.selectType(typename);
-        Document.Properties dprop = new Document.Properties();
-        Document            medoc = getStepService().createDocument(step, dprop.setType(type).setFormat("xml").setAuthor(author)).value();
-        transax.commit();
-
-//      Instantiation of the template into the user download directory
-       if (!udir.exists())  udir.mkdir();
-       if (credoc.exists()) credoc.delete();
-        Do.copy(template, credoc);
-
-//      Transfer to the document of all known properties
-        ResourceBundle   locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
-        SimpleDateFormat get    = new SimpleDateFormat(locale.getString("date.format"));
-        Writer           tool   = Toolbox.getWriter(credoc);
-        List<Step>       slist  = getInvolvedSteps();
-        for (Iterator<Step> i=slist.iterator(); i.hasNext(); ) {
-          List<SimulationContext>            clist = i.next().getAllSimulationContexts();
-          for (Iterator<SimulationContext> j=clist.iterator(); j.hasNext(); ) {
-            SimulationContext   context = j.next();
-            tool.updateProperty(context.getType().getName(), context.getValue());
-          }
-        }
-        tool.updateProperty("reference", medoc.getReference());
-        tool.updateProperty("study",     mystudy.getTitle());
-        tool.updateProperty("step",      locale.getString("folder.step." + step.getNumber()).replaceAll("''", "'"));
-        tool.updateProperty("author",    author.getUsername().toUpperCase());
-        tool.updateProperty("date",      get.format(medoc.getCreationDate()));
-        tool.updateProperty("history",   locale.getString("label.creation").replaceAll("''", "'"));
-        tool.save();
-
-        return new URL(ApplicationSettings.getDownloadURL(author) + filename);
-      }
-      catch (Exception saverror) {
-        logger.error("Reason:", saverror);
-        if (transax != null && transax.isActive()) {
-//        Second try-catch as the rollback could fail as well
-          try {
-               transax.rollback();
-          } catch (HibernateException backerror) {
-            logger.debug("Error rolling back transaction", backerror);
-          }
-        }
-        return null;
-      }
-    }
-
-    public void selectDocument (String docurl) {
-//  ------------------------------------------
-      String  prefix = ApplicationSettings.getRepositoryURL();
-      
-      if (docurl.startsWith(prefix)) try {
-        Session      connex  = Database.getSession();
-        Transaction  transax = connex.beginTransaction();
-        String       path    = docurl.substring(prefix.length());
-        String[]     parse   = path.split("'");
-      
-        path = parse[0];
-        for (int i=1; i<parse.length; i++) path = path + "''" + parse[i];
-//      Better call Database.selectDocument(path), but this service does not exist (overloading issue)
-        String       query   = "from Document where path='" + path + "'";
-        Document     value   = (Document)Database.getSession().createQuery(query).uniqueResult();
-
-        selecdoc = ustep.getDocument(value.getIndex());
-        transax.commit();
-      }
-      catch (Exception error) {
-        logger.error("Reason:", error);
-      }
-    }
-
-    public void setSelection (String step) {
-//  --------------------------------------
-      if (!step.equals(selection)) {
-        selection = step;
-        selecdoc  = null;
-        setupPreviousToSelectedSteps();
-        updateSimulationContexts();                 // Initializes contexts according to the selected steps
-      }
-      ustep      = involving.get(involving.size()-1);
-      urightstep = new StepRights(cuser, ustep);
-      ustep.setActor(cuser);
-      menu.selects(selection);                      // Updates menu items to be displayed
-      setupContents();                              // The contents may have changed even if the selection is the same
-    }    
-
-//  ==============================================================================================================================
-//  Protected services
-//  ==============================================================================================================================
-
-    protected void add (Publication doc) {
-//  ------------------------------------
-         DocumentFacade  facade = new DocumentFacade(this, doc, getProjectSettings(), getPublicationService());
-         boolean         first  = (contents.size() == 0);
-
-      docpres.put(doc.getIndex(), facade);
-      contents.add(0, facade);                          // Prepend the new publication
-      if (first) this.getMenu().refreshSelectedItem();
-
-    }
-
-    protected void add (SimulationContext contex) {
-//  ---------------------------------------------
-      SimulationContextFacade  facade = new SimulationContextFacade(contex, getProjectSettings().getAllSteps());
-
-      context.add(facade);
-    }
-
-    protected void add (KnowledgeElement kelm) {
-//  ------------------------------------------
-      KnowledgeElementFacade  facade = new KnowledgeElementFacade(kelm);
-//RKV      KnowledgeIterator       known  = knowledge.get(kelm.getType().getIndex() - 2);
-                                   // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
-      //RKV:Begin: Find a knowledge iterator for appropriate knowledge type
-      KnowledgeIterator       known  = null;
-      for (KnowledgeIterator aKnowledgeSection : knowledge) {
-         if (aKnowledgeSection.getIndex().equals(String.valueOf(kelm.getType().getIndex()))) {
-                 known = aKnowledgeSection;
-                 break;
-         }
-      }
-      if (known != null) { //RKV:End
-             knowpres.put(kelm.getIndex(), facade);
-             known.list.add(facade);       // Insert the new knowledge at the end of the corresponding knowledge type
-      }
-    }
-
-    protected void remove (Publication doctag) {
-//  ------------------------------------------
-      for (Iterator<DocumentFacade> i=contents.iterator(); i.hasNext(); ) {
-        DocumentFacade  facade = i.next();
-        if (!facade.isFacadeOf(doctag)) continue;
-        i.remove();
-        break;
-      }
-      if (contents.size() == 0) this.getMenu().refreshSelectedItem();
-    }
-
-    protected void changeUser (User user) {
-//  -------------------------------------
-      cuser = user;
-      popup = null;
-      if (mystudy.isStaffedBy(cuser)) {
-        popup = ApplicationSettings.getPopupMenu("steditable");
-           popup.setContext("study", new StudyRights(cuser, mystudy));
-      }
-      ustep.setActor(cuser);
-      urightstudy = new StudyRights(cuser, mystudy);
-      urightstep  = new StepRights(cuser, ustep);
-    }
-
-    protected void remove (SimulationContext contex) {
-//  ------------------------------------------------
-      for (Iterator<SimulationContextFacade> i=context.iterator(); i.hasNext(); ) {
-        SimulationContextFacade  facade = i.next();
-        if (!facade.isFacadeOf(contex)) continue;
-        i.remove();
-        break;
-      }
-    }
-
-    protected void remove (KnowledgeElement kelm) {
-//  ---------------------------------------------
-      KnowledgeIterator       known  = knowledge.get((int)(kelm.getType().getIndex() - 2));
-                                   // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
-      knowpres.remove(kelm.getIndex());
-      for (Iterator<KnowledgeElementFacade> i=known.list.iterator(); i.hasNext(); ) {
-        KnowledgeElementFacade facade = i.next();
-        if (!facade.isFacadeOf(kelm)) continue;
-        i.remove();
-        break;
-      }
-    }
-
-    protected void update (Publication doc) {
-//  ---------------------------------------
-      DocumentFacade facade = docpres.get(doc.getIndex());
-         if (facade != null) {
-               facade.refresh();
-         }
-    }
-
-    protected void update (KnowledgeElement kelm) {
-//  ---------------------------------------------
-         KnowledgeElementFacade facade = knowpres.get(kelm.getIndex());
-         if (facade != null) {
-               facade.refresh();
-         }
-    }
-
-    protected void updateSimulationContexts () {
-//  ------------------------------------------
-      context.clear();
-      for (Iterator<Step> i=involving.iterator(); i.hasNext(); ) {
-        for (Iterator<SimulationContext> j=i.next().getAllSimulationContexts().iterator(); j.hasNext(); ) {
-          context.add( new SimulationContextFacade(j.next(), getProjectSettings().getAllSteps()) );
-        }
-      }
-    }
-
-//  ==============================================================================================================================
-//  Private services
-//  ==============================================================================================================================
-
-    private void setupPreviousToSelectedSteps () {
-//  --------------------------------------------
-      String[] item   = selection.split("\\x2E");
-      int      major  = Integer.valueOf(item[0]);
-      int      minor  = Integer.valueOf(item[1]);
-      int      base   = minor;
-      Step[]   step;
-
-      involving.clear();
-      if (major > 0) {
-       Scenario[] branch = mystudy.getScenarii();
-       Scenario   scenar = branch[0];
-       for (int i=0; i<branch.length; i++) {
-          scenar = branch[i];
-          if (scenar.getIndex() == major) break;      // Supposed exist
-       }
-       step = getProjectElementService().getSteps(scenar);
-       base = step[0].getNumber() - 1;
-       for (int i=0; i+base<minor; i++) {
-               involving.add(step[i]);
-       }
-      }
-      step = getProjectElementService().getSteps(mystudy);
-      for (int i=step.length-1; i>-1; i--) {
-         Step firstep = step[i];
-         if(firstep.getNumber() > base) continue;
-         involving.add(0, firstep);
-      }
-    }
-    
-    /**
-        * Get the projectElementService.
-        * 
-        * @return the projectElementService
+       /**
+        * Injected document type service.
         */
-       public ProjectElementService getProjectElementService() {
-               return _projectElementService;
-       }
+       private DocumentTypeService _documentTypeService;
 
        /**
-        * Set the projectElementService.
-        * 
-        * @param projectElementService
-        *            the projectElementService to set
+        * The injected Study service.
         */
-       public void setProjectElementService(
-                       ProjectElementService projectElementService) {
-               _projectElementService = projectElementService;
-       }
+       private StudyService _studyService;
+
+       // ==============================================================================================================================
+       // Constructor
+       // ==============================================================================================================================
 
        /**
-        * Get the scenarioService.
+        * Open the given study in the current http session.
         * 
-        * @return the scenarioService
+        * @param user
+        *            the current user
+        * @param study
+        *            the study to open
+        * @return this open study object
         */
-       public ScenarioService getScenarioService() {
-               return _scenarioService;
+       public OpenStudy open(User user, Study study) {
+               // -----------------------------------------
+               ResourceBundle custom = ResourceBundle.getBundle("som",
+                               ApplicationSettings.getCurrentLocale());
+               SimpleDateFormat datstring = new SimpleDateFormat(custom
+                               .getString("date.format"));
+               Revision.Format verstring = new Revision.Format(getProjectSettings()
+                               .getRevisionPattern());
+
+               cuser = user; // May be null if nobody connected
+               mystudy = study;
+               selection = "0.1"; // Default selection
+               selecdoc = null;
+
+               // Preparation of the display
+               version = verstring.format(mystudy.getVersion());
+               credate = datstring.format(mystudy.getDate());
+               lasdate = ""; // Not yet supported
+               description = mystudy.getDescription();
+               involving = new ArrayList<Step>(1);
+               context = new ArrayList<SimulationContextFacade>();
+               ustep = getProjectElementService().getFirstStep(mystudy);
+               ustep.setActor(cuser);
+               involving.add(ustep);
+               for (Iterator<SimulationContext> i = ustep.getAllSimulationContexts()
+                               .iterator(); i.hasNext();) {
+                       context.add(new SimulationContextFacade(i.next(),
+                                       getProjectSettings().getAllSteps()));
+               }
+               if (getStudyService().isStaffedBy(mystudy, cuser) || getStudyService().hasActor(mystudy, cuser)) {
+                       // ProgressState state = mystudy.getProgressState();
+                       // if (state == ProgressState.inCHECK) popup = ApplicationSettings.getPopupMenu("stapprovable");
+                       // else if (state == ProgressState.APPROVED) popup = ApplicationSettings.getPopupMenu("stapproved");
+                       /* else */popup = ApplicationSettings
+                                       .getPopupMenu("steditable");
+                       popup.setContext("study", new StudyRights(cuser, mystudy));
+               }
+               urightstudy = new StudyRights(cuser, mystudy);
+               urightstep = new StepRights(cuser, ustep);
+
+               // RKV menu = new StudyMenu(mystudy);
+               menu = ((StudyMenu) getMenu()).init(mystudy); // RKV
+               menu.selects(selection); // Initializes menu items to be displayed
+               setupContents(); // Initializes documents and knowledge at ustep
+               return this;
        }
 
-       /**
-        * Set the scenarioService.
-        * 
-        * @param scenarioService
-        *            the scenarioService to set
-        */
-       public void setScenarioService(ScenarioService scenarioService) {
-               _scenarioService = scenarioService;
+       // ==============================================================================================================================
+       // Getters
+       // ==============================================================================================================================
+
+       public String getAuthorName() {
+               // -----------------------------
+               return mystudy.getAuthor().toString();
+       }
+
+       public Long getIndex() {
+               // -------------------------
+               return mystudy.getIndex();
+       }
+
+       public String getDate() {
+               // ------------------------
+               return credate;
+       }
+
+       public StudyMenu getMenu() {
+               // ---------------------------
+               return (StudyMenu) menu;
+       }
+
+       public void setMenu(StudyMenu aMenu) {
+               menu = aMenu;
+       }
+
+       public ProgressState getProgressState() {
+               // ----------------------------------------
+               return mystudy.getProgressState();
+       }
+
+       public String getLastModificationDate() {
+               // ----------------------------------------
+               return lasdate;
+       }
+
+       public ToolBar getModuleBar() {
+               // ------------------------------
+               return ApplicationSettings.getMe().getModuleBar(getSelectedStep());
+       }
+
+       public String getReference() {
+               // ----------------------------
+               return mystudy.getReference();
+       }
+
+       public Publication getSelectedDocument() {
+               // -----------------------------------------
+               return selecdoc;
+       }
+
+       public StepRights getSelectedStepRights() {
+               // ------------------------------------------
+               return urightstep;
+       }
+
+       public StudyRights getStudyRights() {
+               // ------------------------------------
+               return urightstudy;
+       }
+
+       public Study getStudyObject() {
+               // ------------------------------
+               return mystudy;
+       }
+
+       public String getTitle() {
+               // ------------------------
+               return mystudy.getTitle();
+       }
+
+       public String getType() {
+               // ------------------------
+               return ResourceBundle.getBundle("labels",
+                               ApplicationSettings.getCurrentLocale())
+                               .getString("label.study");
+       }
+
+       public String getVersion() {
+               // ---------------------------
+               return version;
+       }
+
+       public boolean isStepEnabled() {
+               // -------------------------------
+               return urightstep.isEnabled();
+       }
+
+       // ==============================================================================================================================
+       // Public services
+       // ==============================================================================================================================
+
+       public URL newTemplateBasedDocument(String typename, User author) {
+               // ------------------------------------------------------------------
+               String filename = typename + ".xml"; // Only XML templates are writeable
+               File template = new File(getRepositoryService().getTemplatePath()
+                               + filename);
+               if (!template.exists())
+                       return null;
+
+               Session connex = Database.getSession();
+               Transaction transax = connex.beginTransaction();
+               try {
+                       File udir = getRepositoryService().getDownloadDirectory(author);
+                       File credoc = new File(udir.getPath() + "/" + filename);
+
+                       // Creation of the meta-document
+                       Step step = getSelectedStep(); // Should we check if the given document type is compatible ?
+                       DocumentType type = getDocumentTypeService().selectType(typename);
+                       Document.Properties dprop = new Document.Properties();
+                       Document medoc = getStepService().createDocument(step,
+                                       dprop.setType(type).setFormat("xml").setAuthor(author))
+                                       .value();
+                       transax.commit();
+
+                       // Instantiation of the template into the user download directory
+                       if (!udir.exists())
+                               udir.mkdir();
+                       if (credoc.exists())
+                               credoc.delete();
+                       Do.copy(template, credoc);
+
+                       // Transfer to the document of all known properties
+                       ResourceBundle locale = ResourceBundle.getBundle("som",
+                                       ApplicationSettings.getCurrentLocale());
+                       SimpleDateFormat get = new SimpleDateFormat(locale
+                                       .getString("date.format"));
+                       Writer tool = Toolbox.getWriter(credoc);
+                       List<Step> slist = getInvolvedSteps();
+                       for (Iterator<Step> i = slist.iterator(); i.hasNext();) {
+                               List<SimulationContext> clist = i.next()
+                                               .getAllSimulationContexts();
+                               for (Iterator<SimulationContext> j = clist.iterator(); j
+                                               .hasNext();) {
+                                       SimulationContext context = j.next();
+                                       tool.updateProperty(context.getType().getName(), context
+                                                       .getValue());
+                               }
+                       }
+                       tool.updateProperty("reference", medoc.getReference());
+                       tool.updateProperty("study", mystudy.getTitle());
+                       tool.updateProperty("step", locale.getString(
+                                       "folder.step." + step.getNumber()).replaceAll("''", "'"));
+                       tool.updateProperty("author", author.getUsername().toUpperCase());
+                       tool.updateProperty("date", get.format(medoc.getCreationDate()));
+                       tool.updateProperty("history", locale.getString("label.creation")
+                                       .replaceAll("''", "'"));
+                       tool.save();
+
+                       return new URL(ApplicationSettings.getDownloadURL(author)
+                                       + filename);
+               } catch (Exception saverror) {
+                       logger.error("Reason:", saverror);
+                       if (transax != null && transax.isActive()) {
+                               // Second try-catch as the rollback could fail as well
+                               try {
+                                       transax.rollback();
+                               } catch (HibernateException backerror) {
+                                       logger.debug("Error rolling back transaction", backerror);
+                               }
+                       }
+                       return null;
+               }
+       }
+
+       public void selectDocument(String docurl) {
+               // ------------------------------------------
+               String prefix = ApplicationSettings.getRepositoryURL();
+
+               if (docurl.startsWith(prefix))
+                       try {
+                               Session connex = Database.getSession();
+                               Transaction transax = connex.beginTransaction();
+                               String path = docurl.substring(prefix.length());
+                               String[] parse = path.split("'");
+
+                               path = parse[0];
+                               for (int i = 1; i < parse.length; i++)
+                                       path = path + "''" + parse[i];
+                               // Better call Database.selectDocument(path), but this service does not exist (overloading issue)
+                               String query = "from Document where path='" + path + "'";
+                               Document value = (Document) Database.getSession().createQuery(
+                                               query).uniqueResult();
+
+                               selecdoc = ustep.getDocument(value.getIndex());
+                               transax.commit();
+                       } catch (Exception error) {
+                               logger.error("Reason:", error);
+                       }
+       }
+
+       public void setSelection(String step) {
+               // --------------------------------------
+               if (!step.equals(selection)) {
+                       selection = step;
+                       selecdoc = null;
+                       setupPreviousToSelectedSteps();
+                       updateSimulationContexts(); // Initializes contexts according to the selected steps
+               }
+               ustep = involving.get(involving.size() - 1);
+               urightstep = new StepRights(cuser, ustep);
+               ustep.setActor(cuser);
+               menu.selects(selection); // Updates menu items to be displayed
+               setupContents(); // The contents may have changed even if the selection is the same
+       }
+
+       // ==============================================================================================================================
+       // Protected services
+       // ==============================================================================================================================
+
+       protected void add(Publication doc) {
+               // ------------------------------------
+               DocumentFacade facade = new DocumentFacade(this, doc,
+                               getProjectSettings(), getPublicationService());
+               boolean first = (contents.size() == 0);
+
+               docpres.put(doc.getIndex(), facade);
+               contents.add(0, facade); // Prepend the new publication
+               if (first)
+                       this.getMenu().refreshSelectedItem();
+
+       }
+
+       protected void add(SimulationContext contex) {
+               // ---------------------------------------------
+               SimulationContextFacade facade = new SimulationContextFacade(contex,
+                               getProjectSettings().getAllSteps());
+
+               context.add(facade);
+       }
+
+       protected void add(KnowledgeElement kelm) {
+               // ------------------------------------------
+               KnowledgeElementFacade facade = new KnowledgeElementFacade(kelm);
+               // RKV KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
+               // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
+               // RKV:Begin: Find a knowledge iterator for appropriate knowledge type
+               KnowledgeIterator known = null;
+               for (KnowledgeIterator aKnowledgeSection : knowledge) {
+                       if (aKnowledgeSection.getIndex().equals(
+                                       String.valueOf(kelm.getType().getIndex()))) {
+                               known = aKnowledgeSection;
+                               break;
+                       }
+               }
+               if (known != null) { // RKV:End
+                       knowpres.put(kelm.getIndex(), facade);
+                       known.list.add(facade); // Insert the new knowledge at the end of the corresponding knowledge type
+               }
+       }
+
+       protected void remove(Publication doctag) {
+               // ------------------------------------------
+               for (Iterator<DocumentFacade> i = contents.iterator(); i.hasNext();) {
+                       DocumentFacade facade = i.next();
+                       if (!facade.isFacadeOf(doctag))
+                               continue;
+                       i.remove();
+                       break;
+               }
+               if (contents.size() == 0)
+                       this.getMenu().refreshSelectedItem();
+       }
+
+       protected void changeUser(User user) {
+               // -------------------------------------
+               cuser = user;
+               popup = null;
+               if (getStudyService().isStaffedBy(mystudy, cuser)) {
+                       popup = ApplicationSettings.getPopupMenu("steditable");
+                       popup.setContext("study", new StudyRights(cuser, mystudy));
+               }
+               ustep.setActor(cuser);
+               urightstudy = new StudyRights(cuser, mystudy);
+               urightstep = new StepRights(cuser, ustep);
+       }
+
+       protected void remove(SimulationContext contex) {
+               // ------------------------------------------------
+               for (Iterator<SimulationContextFacade> i = context.iterator(); i
+                               .hasNext();) {
+                       SimulationContextFacade facade = i.next();
+                       if (!facade.isFacadeOf(contex))
+                               continue;
+                       i.remove();
+                       break;
+               }
+       }
+
+       protected void remove(KnowledgeElement kelm) {
+               // ---------------------------------------------
+               KnowledgeIterator known = knowledge.get((int) (kelm.getType()
+                               .getIndex() - 2));
+               // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
+               knowpres.remove(kelm.getIndex());
+               for (Iterator<KnowledgeElementFacade> i = known.list.iterator(); i
+                               .hasNext();) {
+                       KnowledgeElementFacade facade = i.next();
+                       if (!facade.isFacadeOf(kelm))
+                               continue;
+                       i.remove();
+                       break;
+               }
+       }
+
+       protected void update(Publication doc) {
+               // ---------------------------------------
+               DocumentFacade facade = docpres.get(doc.getIndex());
+               if (facade != null) {
+                       facade.refresh();
+               }
+       }
+
+       protected void update(KnowledgeElement kelm) {
+               // ---------------------------------------------
+               KnowledgeElementFacade facade = knowpres.get(kelm.getIndex());
+               if (facade != null) {
+                       facade.refresh();
+               }
+       }
+
+       protected void updateSimulationContexts() {
+               // ------------------------------------------
+               context.clear();
+               for (Iterator<Step> i = involving.iterator(); i.hasNext();) {
+                       for (Iterator<SimulationContext> j = i.next()
+                                       .getAllSimulationContexts().iterator(); j.hasNext();) {
+                               context.add(new SimulationContextFacade(j.next(),
+                                               getProjectSettings().getAllSteps()));
+                       }
+               }
+       }
+
+       // ==============================================================================================================================
+       // Private services
+       // ==============================================================================================================================
+
+       private void setupPreviousToSelectedSteps() {
+               // --------------------------------------------
+               String[] item = selection.split("\\x2E");
+               int major = Integer.valueOf(item[0]);
+               int minor = Integer.valueOf(item[1]);
+               int base = minor;
+               Step[] step;
+
+               involving.clear();
+               if (major > 0) {
+                       Scenario[] branch = mystudy.getScenarii();
+                       Scenario scenar = branch[0];
+                       for (int i = 0; i < branch.length; i++) {
+                               scenar = branch[i];
+                               if (scenar.getIndex() == major)
+                                       break; // Supposed exist
+                       }
+                       step = getProjectElementService().getSteps(scenar);
+                       base = step[0].getNumber() - 1;
+                       for (int i = 0; i + base < minor; i++) {
+                               involving.add(step[i]);
+                       }
+               }
+               step = getProjectElementService().getSteps(mystudy);
+               for (int i = step.length - 1; i > -1; i--) {
+                       Step firstep = step[i];
+                       if (firstep.getNumber() > base)
+                               continue;
+                       involving.add(0, firstep);
+               }
        }
 
        /**
         * Get the stepService.
+        * 
         * @return the stepService
         */
        public StepService getStepService() {
@@ -492,7 +515,9 @@ public class OpenStudy extends OpenObject implements OpenStudyServices {
 
        /**
         * Set the stepService.
-        * @param stepService the stepService to set
+        * 
+        * @param stepService
+        *            the stepService to set
         */
        public void setStepService(StepService stepService) {
                _stepService = stepService;
@@ -500,6 +525,7 @@ public class OpenStudy extends OpenObject implements OpenStudyServices {
 
        /**
         * Get the repositoryService.
+        * 
         * @return the repositoryService
         */
        public RepositoryService getRepositoryService() {
@@ -508,9 +534,46 @@ public class OpenStudy extends OpenObject implements OpenStudyServices {
 
        /**
         * Set the repositoryService.
-        * @param repositoryService the repositoryService to set
+        * 
+        * @param repositoryService
+        *            the repositoryService to set
         */
        public void setRepositoryService(RepositoryService repositoryService) {
                _repositoryService = repositoryService;
        }
+
+       /**
+        * Get the documentTypeService.
+        * @return the documentTypeService
+        */
+       public DocumentTypeService getDocumentTypeService() {
+               return _documentTypeService;
+       }
+
+       /**
+        * Set the documentTypeService.
+        * @param documentTypeService the documentTypeService to set
+        */
+       public void setDocumentTypeService(DocumentTypeService documentTypeService) {
+               _documentTypeService = documentTypeService;
+       }
+
+       /**
+        * Get the studyService.
+        * 
+        * @return the studyService
+        */
+       public StudyService getStudyService() {
+               return _studyService;
+       }
+
+       /**
+        * Set the studyService.
+        * 
+        * @param studyService
+        *            the studyService to set
+        */
+       public void setStudyService(StudyService studyService) {
+               _studyService = studyService;
+       }
 }
\ No newline at end of file