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