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