]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman/src/org/splat/simer/OpenStudy.java
Salome HOME
Addition of a new scenario to a study is fixed. StudyMenu and NewScenarioMenu are...
[tools/siman.git] / Workspace / Siman / src / org / splat / simer / OpenStudy.java
1 package org.splat.simer;
2 /**
3  * 
4  * @author    Daniel Brunier-Coulin
5  * @copyright OPEN CASCADE 2012
6  */
7
8 import java.io.File;
9 import java.net.URL;
10 import java.text.SimpleDateFormat;
11 import java.util.ArrayList;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.ResourceBundle;
15
16 import org.apache.log4j.Logger;
17 import org.hibernate.HibernateException;
18 import org.hibernate.Session;
19 import org.hibernate.Transaction;
20 import org.splat.kernel.Do;
21 import org.splat.dal.bo.kernel.User;
22 import org.splat.manox.Toolbox;
23 import org.splat.manox.Writer;
24 import org.splat.dal.dao.som.Database;
25 import org.splat.dal.bo.som.Document;
26 import org.splat.dal.bo.som.DocumentType;
27 import org.splat.dal.bo.som.KnowledgeElement;
28 import org.splat.dal.bo.som.ProgressState;
29 import org.splat.service.ProjectElementService;
30 import org.splat.service.ScenarioService;
31 import org.splat.service.StepService;
32 import org.splat.service.technical.RepositoryService;
33 import org.splat.dal.bo.som.Publication;
34 import org.splat.som.Revision;
35 import org.splat.dal.bo.som.Scenario;
36 import org.splat.dal.bo.som.SimulationContext;
37 import org.splat.som.Step;
38 import org.splat.som.StepRights;
39 import org.splat.dal.bo.som.Study;
40 import org.splat.som.StudyRights;
41 import org.splat.wapp.Menu;
42 import org.splat.wapp.ToolBar;
43
44
45 public class OpenStudy extends OpenObject implements OpenStudyServices {
46
47         /**
48          * Serial version ID.
49          */
50         protected final static Logger   logger = org.splat.simer.Action.logger;
51     
52     private  Study       mystudy;
53     private  StudyRights urightstudy;              // User rights on the open study
54         private  StepRights  urightstep;               // User rights on the selected step
55     private  String      version;
56     private  String      credate;
57     private  String      lasdate;
58     private  Publication selecdoc;
59         /**
60          * Injected project element service.
61          */
62         private ProjectElementService _projectElementService;
63         /**
64          * Injected scenario service.
65          */
66         private ScenarioService _scenarioService;
67         /**
68          * Injected step service.
69          */
70         private StepService _stepService;
71         /**
72          * Injected repository service.
73          */
74         private RepositoryService _repositoryService;
75 //  ==============================================================================================================================
76 //  Constructor
77 //  ==============================================================================================================================
78
79     /**
80      * Open the given study in the current http session.
81      * @param user the current user
82      * @param study the study to open
83      * @return this open study object
84      */
85     public OpenStudy open (User user, Study study) {
86 //  -----------------------------------------
87       ResourceBundle    custom    = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
88       SimpleDateFormat  datstring = new SimpleDateFormat(custom.getString("date.format"));
89       Revision.Format   verstring = new Revision.Format(getProjectSettings().getRevisionPattern());
90         
91       cuser       = user;                           // May be null if nobody connected
92       mystudy     = study;
93       selection   = "0.1";                          // Default selection
94       selecdoc    = null;
95
96 //    Preparation of the display
97       version     = verstring.format(mystudy.getVersion());
98       credate     = datstring.format(mystudy.getDate());
99       lasdate     = "";                             // Not yet supported
100       description = mystudy.getDescription();
101       involving   = new ArrayList<Step>(1);
102       context     = new ArrayList<SimulationContextFacade>();
103       ustep       = getProjectElementService().getFirstStep(mystudy);
104       ustep.setActor(cuser);
105       involving.add(ustep);
106       for (Iterator<SimulationContext> i=ustep.getAllSimulationContexts().iterator(); i.hasNext(); ) {
107         context.add( new SimulationContextFacade(i.next(), getProjectSettings().getAllSteps()) );
108       }
109       if (mystudy.isStaffedBy(cuser) || mystudy.hasActor(cuser)) {
110 //      ProgressState state = mystudy.getProgressState();
111 //          if           (state == ProgressState.inCHECK)  popup = ApplicationSettings.getPopupMenu("stapprovable");
112 //          else if      (state == ProgressState.APPROVED) popup = ApplicationSettings.getPopupMenu("stapproved");
113 /*      else         */                                popup = ApplicationSettings.getPopupMenu("steditable");
114             popup.setContext("study", new StudyRights(cuser, mystudy));
115       }
116       urightstudy = new StudyRights(cuser, mystudy);
117       urightstep  = new StepRights(cuser, ustep);
118
119 //RKV      menu = new StudyMenu(mystudy);
120       menu = ((StudyMenu)getMenu()).init(mystudy); //RKV
121       ((StudyMenu)menu).setProjectElementService(getProjectElementService());
122       ((StudyMenu)menu).setScenarioService(getScenarioService());
123       menu.selects(selection);                      // Initializes menu items to be displayed
124       setupContents();                              // Initializes documents and knowledge at ustep
125       return this;
126     }
127
128 //  ==============================================================================================================================
129 //  Getters
130 //  ==============================================================================================================================
131
132         public String getAuthorName() {
133 //  -----------------------------
134       return mystudy.getAuthor().toString();
135     }
136     public Long getIndex() {
137 //  -------------------------
138       return mystudy.getIndex();
139     }
140     public String getDate () {
141 //  ------------------------
142       return credate;
143     }
144     public StudyMenu getMenu () {
145 //  ---------------------------
146       return (StudyMenu)menu;
147     }
148     public ProgressState getProgressState() {
149 //  ----------------------------------------
150       return mystudy.getProgressState();
151     }
152     public String getLastModificationDate () {
153 //  ----------------------------------------
154       return lasdate;
155     }
156     public ToolBar getModuleBar () {
157 //  ------------------------------
158       return ApplicationSettings.getMe().getModuleBar(getSelectedStep());
159     }
160     public String getReference() {
161 //  ----------------------------
162       return mystudy.getReference();
163     }
164     public Publication getSelectedDocument () {
165 //  -----------------------------------------
166       return selecdoc;
167     }
168     public StepRights getSelectedStepRights () {
169 //  ------------------------------------------
170       return urightstep;
171     }
172     public StudyRights getStudyRights () {
173 //  ------------------------------------
174       return urightstudy;
175     }
176     public Study getStudyObject () {
177 //  ------------------------------
178       return mystudy;
179     }
180     public String getTitle() {
181 //  ------------------------
182       return mystudy.getTitle();
183     }
184     public String getType () {
185 //  ------------------------
186       return ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale()).getString("label.study");
187     }
188     public String getVersion () {
189 //  ---------------------------
190       return version;
191     }
192     public boolean isStepEnabled () {
193 //  -------------------------------
194       return urightstep.isEnabled();
195     }
196
197 //  ==============================================================================================================================
198 //  Public services
199 //  ==============================================================================================================================
200
201     public URL newTemplateBasedDocument (String typename, User author) {
202 //  ------------------------------------------------------------------
203       String filename = typename + ".xml";     // Only XML templates are writeable
204       File   template = new File(getRepositoryService().getTemplatePath() + filename);      
205       if   (!template.exists()) return null;
206       
207       Session      connex  = Database.getSession();
208           Transaction  transax = connex.beginTransaction();
209       try {
210         File  udir   = getRepositoryService().getDownloadDirectory(author);
211         File  credoc = new File(udir.getPath() + "/" + filename);
212
213 //      Creation of the meta-document
214         Step                step  = getSelectedStep();   // Should we check if the given document type is compatible ?
215             DocumentType        type  = Document.selectType(typename);
216         Document.Properties dprop = new Document.Properties();
217         Document            medoc = getStepService().createDocument(step, dprop.setType(type).setFormat("xml").setAuthor(author)).value();
218         transax.commit();
219
220 //      Instantiation of the template into the user download directory
221         if (!udir.exists())  udir.mkdir();
222         if (credoc.exists()) credoc.delete();
223         Do.copy(template, credoc);
224
225 //      Transfer to the document of all known properties
226         ResourceBundle   locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
227         SimpleDateFormat get    = new SimpleDateFormat(locale.getString("date.format"));
228         Writer           tool   = Toolbox.getWriter(credoc);
229         List<Step>       slist  = getInvolvedSteps();
230         for (Iterator<Step> i=slist.iterator(); i.hasNext(); ) {
231           List<SimulationContext>            clist = i.next().getAllSimulationContexts();
232           for (Iterator<SimulationContext> j=clist.iterator(); j.hasNext(); ) {
233             SimulationContext   context = j.next();
234             tool.updateProperty(context.getType().getName(), context.getValue());
235           }
236         }
237         tool.updateProperty("reference", medoc.getReference());
238         tool.updateProperty("study",     mystudy.getTitle());
239         tool.updateProperty("step",      locale.getString("folder.step." + step.getNumber()).replaceAll("''", "'"));
240         tool.updateProperty("author",    author.getUsername().toUpperCase());
241         tool.updateProperty("date",      get.format(medoc.getCreationDate()));
242         tool.updateProperty("history",   locale.getString("label.creation").replaceAll("''", "'"));
243         tool.save();
244
245         return new URL(ApplicationSettings.getDownloadURL(author) + filename);
246       }
247       catch (Exception saverror) {
248         logger.error("Reason:", saverror);
249         if (transax != null && transax.isActive()) {
250 //        Second try-catch as the rollback could fail as well
251           try {
252                 transax.rollback();
253           } catch (HibernateException backerror) {
254             logger.debug("Error rolling back transaction", backerror);
255           }
256         }
257         return null;
258       }
259     }
260
261     public void selectDocument (String docurl) {
262 //  ------------------------------------------
263       String  prefix = ApplicationSettings.getRepositoryURL();
264       
265       if (docurl.startsWith(prefix)) try {
266         Session      connex  = Database.getSession();
267         Transaction  transax = connex.beginTransaction();
268         String       path    = docurl.substring(prefix.length());
269         String[]     parse   = path.split("'");
270       
271         path = parse[0];
272         for (int i=1; i<parse.length; i++) path = path + "''" + parse[i];
273 //      Better call Database.selectDocument(path), but this service does not exist (overloading issue)
274         String       query   = "from Document where path='" + path + "'";
275         Document     value   = (Document)Database.getSession().createQuery(query).uniqueResult();
276
277         selecdoc = ustep.getDocument(value.getIndex());
278         transax.commit();
279       }
280       catch (Exception error) {
281         logger.error("Reason:", error);
282       }
283     }
284
285     public void setSelection (String step) {
286 //  --------------------------------------
287       if (!step.equals(selection)) {
288         selection = step;
289         selecdoc  = null;
290         setupPreviousToSelectedSteps();
291         updateSimulationContexts();                 // Initializes contexts according to the selected steps
292       }
293       ustep      = involving.get(involving.size()-1);
294       urightstep = new StepRights(cuser, ustep);
295       ustep.setActor(cuser);
296       menu.selects(selection);                      // Updates menu items to be displayed
297       setupContents();                              // The contents may have changed even if the selection is the same
298     }    
299
300 //  ==============================================================================================================================
301 //  Protected services
302 //  ==============================================================================================================================
303
304     protected void add (Publication doc) {
305 //  ------------------------------------
306           DocumentFacade  facade = new DocumentFacade(this, doc, getProjectSettings(), getPublicationService());
307           boolean         first  = (contents.size() == 0);
308
309       docpres.put(doc.getIndex(), facade);
310       contents.add(0, facade);                          // Prepend the new publication
311       if (first) this.getMenu().refreshSelectedItem();
312
313     }
314
315     protected void add (SimulationContext contex) {
316 //  ---------------------------------------------
317       SimulationContextFacade  facade = new SimulationContextFacade(contex, getProjectSettings().getAllSteps());
318
319       context.add(facade);
320     }
321
322     protected void add (KnowledgeElement kelm) {
323 //  ------------------------------------------
324       KnowledgeElementFacade  facade = new KnowledgeElementFacade(kelm);
325 //RKV      KnowledgeIterator       known  = knowledge.get(kelm.getType().getIndex() - 2);
326                                     // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
327       //RKV:Begin: Find a knowledge iterator for appropriate knowledge type
328       KnowledgeIterator       known  = null;
329       for (KnowledgeIterator aKnowledgeSection : knowledge) {
330           if (aKnowledgeSection.getIndex().equals(String.valueOf(kelm.getType().getIndex()))) {
331                   known = aKnowledgeSection;
332                   break;
333           }
334       }
335       if (known != null) { //RKV:End
336               knowpres.put(kelm.getIndex(), facade);
337               known.list.add(facade);       // Insert the new knowledge at the end of the corresponding knowledge type
338       }
339     }
340
341     protected void remove (Publication doctag) {
342 //  ------------------------------------------
343       for (Iterator<DocumentFacade> i=contents.iterator(); i.hasNext(); ) {
344         DocumentFacade  facade = i.next();
345         if (!facade.isFacadeOf(doctag)) continue;
346         i.remove();
347         break;
348       }
349       if (contents.size() == 0) this.getMenu().refreshSelectedItem();
350     }
351
352     protected void changeUser (User user) {
353 //  -------------------------------------
354       cuser = user;
355       popup = null;
356       if (mystudy.isStaffedBy(cuser)) {
357         popup = ApplicationSettings.getPopupMenu("steditable");
358             popup.setContext("study", new StudyRights(cuser, mystudy));
359       }
360       ustep.setActor(cuser);
361       urightstudy = new StudyRights(cuser, mystudy);
362       urightstep  = new StepRights(cuser, ustep);
363     }
364
365     protected void remove (SimulationContext contex) {
366 //  ------------------------------------------------
367       for (Iterator<SimulationContextFacade> i=context.iterator(); i.hasNext(); ) {
368         SimulationContextFacade  facade = i.next();
369         if (!facade.isFacadeOf(contex)) continue;
370         i.remove();
371         break;
372       }
373     }
374
375     protected void remove (KnowledgeElement kelm) {
376 //  ---------------------------------------------
377       KnowledgeIterator       known  = knowledge.get((int)(kelm.getType().getIndex() - 2));
378                                     // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
379       knowpres.remove(kelm.getIndex());
380       for (Iterator<KnowledgeElementFacade> i=known.list.iterator(); i.hasNext(); ) {
381         KnowledgeElementFacade facade = i.next();
382         if (!facade.isFacadeOf(kelm)) continue;
383         i.remove();
384         break;
385       }
386     }
387
388     protected void update (Publication doc) {
389 //  ---------------------------------------
390       DocumentFacade facade = docpres.get(doc.getIndex());
391           if (facade != null) {
392                 facade.refresh();
393           }
394     }
395
396     protected void update (KnowledgeElement kelm) {
397 //  ---------------------------------------------
398           KnowledgeElementFacade facade = knowpres.get(kelm.getIndex());
399           if (facade != null) {
400                 facade.refresh();
401           }
402     }
403
404     protected void updateSimulationContexts () {
405 //  ------------------------------------------
406       context.clear();
407       for (Iterator<Step> i=involving.iterator(); i.hasNext(); ) {
408         for (Iterator<SimulationContext> j=i.next().getAllSimulationContexts().iterator(); j.hasNext(); ) {
409           context.add( new SimulationContextFacade(j.next(), getProjectSettings().getAllSteps()) );
410         }
411       }
412     }
413
414 //  ==============================================================================================================================
415 //  Private services
416 //  ==============================================================================================================================
417
418     private void setupPreviousToSelectedSteps () {
419 //  --------------------------------------------
420       String[] item   = selection.split("\\x2E");
421       int      major  = Integer.valueOf(item[0]);
422       int      minor  = Integer.valueOf(item[1]);
423       int      base   = minor;
424       Step[]   step;
425
426       involving.clear();
427       if (major > 0) {
428         Scenario[] branch = mystudy.getScenarii();
429         Scenario   scenar = branch[0];
430         for (int i=0; i<branch.length; i++) {
431           scenar = branch[i];
432           if (scenar.getIndex() == major) break;      // Supposed exist
433         }
434         step = getProjectElementService().getSteps(scenar);
435         base = step[0].getNumber() - 1;
436         for (int i=0; i+base<minor; i++) {
437                 involving.add(step[i]);
438         }
439       }
440       step = getProjectElementService().getSteps(mystudy);
441       for (int i=step.length-1; i>-1; i--) {
442           Step firstep = step[i];
443           if(firstep.getNumber() > base) continue;
444           involving.add(0, firstep);
445       }
446     }
447     
448     /**
449          * Get the projectElementService.
450          * 
451          * @return the projectElementService
452          */
453         public ProjectElementService getProjectElementService() {
454                 return _projectElementService;
455         }
456
457         /**
458          * Set the projectElementService.
459          * 
460          * @param projectElementService
461          *            the projectElementService to set
462          */
463         public void setProjectElementService(
464                         ProjectElementService projectElementService) {
465                 _projectElementService = projectElementService;
466         }
467
468         /**
469          * Get the scenarioService.
470          * 
471          * @return the scenarioService
472          */
473         public ScenarioService getScenarioService() {
474                 return _scenarioService;
475         }
476
477         /**
478          * Set the scenarioService.
479          * 
480          * @param scenarioService
481          *            the scenarioService to set
482          */
483         public void setScenarioService(ScenarioService scenarioService) {
484                 _scenarioService = scenarioService;
485         }
486
487         /**
488          * Get the stepService.
489          * @return the stepService
490          */
491         public StepService getStepService() {
492                 return _stepService;
493         }
494
495         /**
496          * Set the stepService.
497          * @param stepService the stepService to set
498          */
499         public void setStepService(StepService stepService) {
500                 _stepService = stepService;
501         }
502
503         /**
504          * Get the repositoryService.
505          * @return the repositoryService
506          */
507         public RepositoryService getRepositoryService() {
508                 return _repositoryService;
509         }
510
511         /**
512          * Set the repositoryService.
513          * @param repositoryService the repositoryService to set
514          */
515         public void setRepositoryService(RepositoryService repositoryService) {
516                 _repositoryService = repositoryService;
517         }
518 }