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