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