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