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