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