1 package org.splat.simer;
5 * @author Daniel Brunier-Coulin
6 * @copyright OPEN CASCADE 2012
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;
17 import org.apache.log4j.Logger;
18 import org.hibernate.HibernateException;
19 import org.hibernate.Session;
20 import org.hibernate.Transaction;
21 import org.splat.kernel.Do;
22 import org.splat.dal.bo.kernel.User;
23 import org.splat.manox.Toolbox;
24 import org.splat.manox.Writer;
25 import org.splat.dal.dao.som.Database;
26 import org.splat.dal.bo.som.Document;
27 import org.splat.dal.bo.som.DocumentType;
28 import org.splat.dal.bo.som.KnowledgeElement;
29 import org.splat.dal.bo.som.ProgressState;
30 import org.splat.service.DocumentTypeService;
31 import org.splat.service.StepService;
32 import org.splat.service.StudyService;
33 import org.splat.service.technical.RepositoryService;
34 import org.splat.dal.bo.som.Publication;
35 import org.splat.som.Revision;
36 import org.splat.dal.bo.som.Scenario;
37 import org.splat.dal.bo.som.SimulationContext;
38 import org.splat.som.Step;
39 import org.splat.som.StepRights;
40 import org.splat.dal.bo.som.Study;
41 import org.splat.som.StudyRights;
42 import org.splat.wapp.ToolBar;
44 public class OpenStudy extends OpenObject implements OpenStudyServices {
49 protected final static Logger logger = org.splat.simer.Action.logger;
51 private Study mystudy;
52 private StudyRights urightstudy; // User rights on the open study
53 private StepRights urightstep; // User rights on the selected step
54 private String version;
55 private String credate;
56 private String lasdate;
57 private Publication selecdoc;
59 * Injected step service.
61 private StepService _stepService;
63 * Injected repository service.
65 private RepositoryService _repositoryService;
67 * Injected document type service.
69 private DocumentTypeService _documentTypeService;
72 * The injected Study service.
74 private StudyService _studyService;
76 // ==============================================================================================================================
78 // ==============================================================================================================================
81 * Open the given study in the current http session.
87 * @return this open study object
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());
98 cuser = user; // May be null if nobody connected
100 selection = "0.1"; // Default selection
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()));
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));
126 urightstudy = new StudyRights(cuser, mystudy);
127 urightstep = new StepRights(cuser, ustep);
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
136 // ==============================================================================================================================
138 // ==============================================================================================================================
140 public String getAuthorName() {
141 // -----------------------------
142 return mystudy.getAuthor().toString();
145 public Long getIndex() {
146 // -------------------------
147 return mystudy.getIndex();
150 public String getDate() {
151 // ------------------------
155 public StudyMenu getMenu() {
156 // ---------------------------
157 return (StudyMenu) menu;
160 public void setMenu(StudyMenu aMenu) {
164 public ProgressState getProgressState() {
165 // ----------------------------------------
166 return mystudy.getProgressState();
169 public String getLastModificationDate() {
170 // ----------------------------------------
174 public ToolBar getModuleBar() {
175 // ------------------------------
176 return ApplicationSettings.getMe().getModuleBar(getSelectedStep());
179 public String getReference() {
180 // ----------------------------
181 return mystudy.getReference();
184 public Publication getSelectedDocument() {
185 // -----------------------------------------
189 public StepRights getSelectedStepRights() {
190 // ------------------------------------------
194 public StudyRights getStudyRights() {
195 // ------------------------------------
199 public Study getStudyObject() {
200 // ------------------------------
204 public String getTitle() {
205 // ------------------------
206 return mystudy.getTitle();
209 public String getType() {
210 // ------------------------
211 return ResourceBundle.getBundle("labels",
212 ApplicationSettings.getCurrentLocale())
213 .getString("label.study");
216 public String getVersion() {
217 // ---------------------------
221 public boolean isStepEnabled() {
222 // -------------------------------
223 return urightstep.isEnabled();
226 // ==============================================================================================================================
228 // ==============================================================================================================================
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()
235 if (!template.exists())
238 Session connex = Database.getSession();
239 Transaction transax = connex.beginTransaction();
241 File udir = getRepositoryService().getDownloadDirectory(author);
242 File credoc = new File(udir.getPath() + "/" + filename);
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))
253 // Instantiation of the template into the user download directory
258 Do.copy(template, credoc);
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
272 SimulationContext context = j.next();
273 tool.updateProperty(context.getType().getName(), context
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("''", "'"));
287 return new URL(ApplicationSettings.getDownloadURL(author)
289 } catch (Exception saverror) {
290 logger.error("Reason:", saverror);
291 if (transax != null && transax.isActive()) {
292 // Second try-catch as the rollback could fail as well
295 } catch (HibernateException backerror) {
296 logger.debug("Error rolling back transaction", backerror);
303 public void selectDocument(String docurl) {
304 // ------------------------------------------
305 String prefix = ApplicationSettings.getRepositoryURL();
307 if (docurl.startsWith(prefix))
309 Session connex = Database.getSession();
310 Transaction transax = connex.beginTransaction();
311 String path = docurl.substring(prefix.length());
312 String[] parse = path.split("'");
315 for (int i = 1; i < parse.length; i++)
316 path = path + "''" + parse[i];
317 // Better call Database.selectDocument(path), but this service does not exist (overloading issue)
318 String query = "from Document where path='" + path + "'";
319 Document value = (Document) Database.getSession().createQuery(
320 query).uniqueResult();
322 selecdoc = ustep.getDocument(value.getIndex());
324 } catch (Exception error) {
325 logger.error("Reason:", error);
329 public void setSelection(String step) {
330 // --------------------------------------
331 if (!step.equals(selection)) {
334 setupPreviousToSelectedSteps();
335 updateSimulationContexts(); // Initializes contexts according to the selected steps
337 ustep = involving.get(involving.size() - 1);
338 urightstep = new StepRights(cuser, ustep);
339 ustep.setActor(cuser);
340 menu.selects(selection); // Updates menu items to be displayed
341 setupContents(); // The contents may have changed even if the selection is the same
344 // ==============================================================================================================================
345 // Protected services
346 // ==============================================================================================================================
348 protected void add(Publication doc) {
349 // ------------------------------------
350 DocumentFacade facade = new DocumentFacade(this, doc,
351 getProjectSettings(), getPublicationService());
352 boolean first = (contents.size() == 0);
354 docpres.put(doc.getIndex(), facade);
355 contents.add(0, facade); // Prepend the new publication
357 this.getMenu().refreshSelectedItem();
361 protected void add(SimulationContext contex) {
362 // ---------------------------------------------
363 SimulationContextFacade facade = new SimulationContextFacade(contex,
364 getProjectSettings().getAllSteps());
369 protected void add(KnowledgeElement kelm) {
370 // ------------------------------------------
371 KnowledgeElementFacade facade = new KnowledgeElementFacade(kelm);
372 // RKV KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
373 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
374 // RKV:Begin: Find a knowledge iterator for appropriate knowledge type
375 KnowledgeIterator known = null;
376 for (KnowledgeIterator aKnowledgeSection : knowledge) {
377 if (aKnowledgeSection.getIndex().equals(
378 String.valueOf(kelm.getType().getIndex()))) {
379 known = aKnowledgeSection;
383 if (known != null) { // RKV:End
384 knowpres.put(kelm.getIndex(), facade);
385 known.list.add(facade); // Insert the new knowledge at the end of the corresponding knowledge type
389 protected void remove(Publication doctag) {
390 // ------------------------------------------
391 for (Iterator<DocumentFacade> i = contents.iterator(); i.hasNext();) {
392 DocumentFacade facade = i.next();
393 if (!facade.isFacadeOf(doctag))
398 if (contents.size() == 0)
399 this.getMenu().refreshSelectedItem();
402 protected void changeUser(User user) {
403 // -------------------------------------
406 if (getStudyService().isStaffedBy(mystudy, cuser)) {
407 popup = ApplicationSettings.getPopupMenu("steditable");
408 popup.setContext("study", new StudyRights(cuser, mystudy));
410 ustep.setActor(cuser);
411 urightstudy = new StudyRights(cuser, mystudy);
412 urightstep = new StepRights(cuser, ustep);
415 protected void remove(SimulationContext contex) {
416 // ------------------------------------------------
417 for (Iterator<SimulationContextFacade> i = context.iterator(); i
419 SimulationContextFacade facade = i.next();
420 if (!facade.isFacadeOf(contex))
427 protected void remove(KnowledgeElement kelm) {
428 // ---------------------------------------------
429 KnowledgeIterator known = knowledge.get((int) (kelm.getType()
431 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
432 knowpres.remove(kelm.getIndex());
433 for (Iterator<KnowledgeElementFacade> i = known.list.iterator(); i
435 KnowledgeElementFacade facade = i.next();
436 if (!facade.isFacadeOf(kelm))
443 protected void update(Publication doc) {
444 // ---------------------------------------
445 DocumentFacade facade = docpres.get(doc.getIndex());
446 if (facade != null) {
451 protected void update(KnowledgeElement kelm) {
452 // ---------------------------------------------
453 KnowledgeElementFacade facade = knowpres.get(kelm.getIndex());
454 if (facade != null) {
459 protected void updateSimulationContexts() {
460 // ------------------------------------------
462 for (Iterator<Step> i = involving.iterator(); i.hasNext();) {
463 for (Iterator<SimulationContext> j = i.next()
464 .getAllSimulationContexts().iterator(); j.hasNext();) {
465 context.add(new SimulationContextFacade(j.next(),
466 getProjectSettings().getAllSteps()));
471 // ==============================================================================================================================
473 // ==============================================================================================================================
475 private void setupPreviousToSelectedSteps() {
476 // --------------------------------------------
477 String[] item = selection.split("\\x2E");
478 int major = Integer.valueOf(item[0]);
479 int minor = Integer.valueOf(item[1]);
485 Scenario[] branch = mystudy.getScenarii();
486 Scenario scenar = branch[0];
487 for (int i = 0; i < branch.length; i++) {
489 if (scenar.getIndex() == major)
490 break; // Supposed exist
492 step = getProjectElementService().getSteps(scenar);
493 base = step[0].getNumber() - 1;
494 for (int i = 0; i + base < minor; i++) {
495 involving.add(step[i]);
498 step = getProjectElementService().getSteps(mystudy);
499 for (int i = step.length - 1; i > -1; i--) {
500 Step firstep = step[i];
501 if (firstep.getNumber() > base)
503 involving.add(0, firstep);
508 * Get the stepService.
510 * @return the stepService
512 public StepService getStepService() {
517 * Set the stepService.
520 * the stepService to set
522 public void setStepService(StepService stepService) {
523 _stepService = stepService;
527 * Get the repositoryService.
529 * @return the repositoryService
531 public RepositoryService getRepositoryService() {
532 return _repositoryService;
536 * Set the repositoryService.
538 * @param repositoryService
539 * the repositoryService to set
541 public void setRepositoryService(RepositoryService repositoryService) {
542 _repositoryService = repositoryService;
546 * Get the documentTypeService.
547 * @return the documentTypeService
549 public DocumentTypeService getDocumentTypeService() {
550 return _documentTypeService;
554 * Set the documentTypeService.
555 * @param documentTypeService the documentTypeService to set
557 public void setDocumentTypeService(DocumentTypeService documentTypeService) {
558 _documentTypeService = documentTypeService;
562 * Get the studyService.
564 * @return the studyService
566 public StudyService getStudyService() {
567 return _studyService;
571 * Set the studyService.
573 * @param studyService
574 * the studyService to set
576 public void setStudyService(StudyService studyService) {
577 _studyService = studyService;