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