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