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