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