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