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