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