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