1 package org.splat.simer;
4 * @author Daniel Brunier-Coulin
5 * @copyright OPEN CASCADE 2012
10 import java.text.SimpleDateFormat;
11 import java.util.ArrayList;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.ResourceBundle;
16 import org.apache.log4j.Logger;
17 import org.hibernate.HibernateException;
18 import org.hibernate.Session;
19 import org.hibernate.Transaction;
20 import org.splat.kernel.Do;
21 import org.splat.dal.bo.kernel.User;
22 import org.splat.manox.Toolbox;
23 import org.splat.manox.Writer;
24 import org.splat.dal.dao.som.Database;
25 import org.splat.dal.bo.som.Document;
26 import org.splat.dal.bo.som.DocumentType;
27 import org.splat.dal.bo.som.KnowledgeElement;
28 import org.splat.dal.bo.som.ProgressState;
29 import org.splat.service.ProjectElementService;
30 import org.splat.service.ScenarioService;
31 import org.splat.service.StepService;
32 import org.splat.service.technical.RepositoryService;
33 import org.splat.dal.bo.som.Publication;
34 import org.splat.som.Revision;
35 import org.splat.dal.bo.som.Scenario;
36 import org.splat.dal.bo.som.SimulationContext;
37 import org.splat.som.Step;
38 import org.splat.som.StepRights;
39 import org.splat.dal.bo.som.Study;
40 import org.splat.som.StudyRights;
41 import org.splat.wapp.Menu;
42 import org.splat.wapp.ToolBar;
45 public class OpenStudy extends OpenObject implements OpenStudyServices {
50 protected final static Logger logger = org.splat.simer.Action.logger;
52 private Study mystudy;
53 private StudyRights urightstudy; // User rights on the open study
54 private StepRights urightstep; // User rights on the selected step
55 private String version;
56 private String credate;
57 private String lasdate;
58 private Publication selecdoc;
60 * Injected project element service.
62 private ProjectElementService _projectElementService;
64 * Injected scenario service.
66 private ScenarioService _scenarioService;
68 * Injected step service.
70 private StepService _stepService;
72 * Injected repository service.
74 private RepositoryService _repositoryService;
75 // ==============================================================================================================================
77 // ==============================================================================================================================
80 * Open the given study in the current http session.
81 * @param user the current user
82 * @param study the study to open
83 * @return this open study object
85 public OpenStudy open (User user, Study study) {
86 // -----------------------------------------
87 ResourceBundle custom = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
88 SimpleDateFormat datstring = new SimpleDateFormat(custom.getString("date.format"));
89 Revision.Format verstring = new Revision.Format(getProjectSettings().getRevisionPattern());
91 cuser = user; // May be null if nobody connected
93 selection = "0.1"; // Default selection
96 // Preparation of the display
97 version = verstring.format(mystudy.getVersion());
98 credate = datstring.format(mystudy.getDate());
99 lasdate = ""; // Not yet supported
100 description = mystudy.getDescription();
101 involving = new ArrayList<Step>(1);
102 context = new ArrayList<SimulationContextFacade>();
103 ustep = getProjectElementService().getFirstStep(mystudy);
104 ustep.setActor(cuser);
105 involving.add(ustep);
106 for (Iterator<SimulationContext> i=ustep.getAllSimulationContexts().iterator(); i.hasNext(); ) {
107 context.add( new SimulationContextFacade(i.next(), getProjectSettings().getAllSteps()) );
109 if (mystudy.isStaffedBy(cuser) || mystudy.hasActor(cuser)) {
110 // ProgressState state = mystudy.getProgressState();
111 // if (state == ProgressState.inCHECK) popup = ApplicationSettings.getPopupMenu("stapprovable");
112 // else if (state == ProgressState.APPROVED) popup = ApplicationSettings.getPopupMenu("stapproved");
113 /* else */ popup = ApplicationSettings.getPopupMenu("steditable");
114 popup.setContext("study", new StudyRights(cuser, mystudy));
116 urightstudy = new StudyRights(cuser, mystudy);
117 urightstep = new StepRights(cuser, ustep);
119 //RKV menu = new StudyMenu(mystudy);
120 menu = ((StudyMenu)getMenu()).init(mystudy); //RKV
121 ((StudyMenu)menu).setProjectElementService(getProjectElementService());
122 ((StudyMenu)menu).setScenarioService(getScenarioService());
123 menu.selects(selection); // Initializes menu items to be displayed
124 setupContents(); // Initializes documents and knowledge at ustep
128 // ==============================================================================================================================
130 // ==============================================================================================================================
132 public String getAuthorName() {
133 // -----------------------------
134 return mystudy.getAuthor().toString();
136 public Long getIndex() {
137 // -------------------------
138 return mystudy.getIndex();
140 public String getDate () {
141 // ------------------------
144 public StudyMenu getMenu () {
145 // ---------------------------
146 return (StudyMenu)menu;
148 public ProgressState getProgressState() {
149 // ----------------------------------------
150 return mystudy.getProgressState();
152 public String getLastModificationDate () {
153 // ----------------------------------------
156 public ToolBar getModuleBar () {
157 // ------------------------------
158 return ApplicationSettings.getMe().getModuleBar(getSelectedStep());
160 public String getReference() {
161 // ----------------------------
162 return mystudy.getReference();
164 public Publication getSelectedDocument () {
165 // -----------------------------------------
168 public StepRights getSelectedStepRights () {
169 // ------------------------------------------
172 public StudyRights getStudyRights () {
173 // ------------------------------------
176 public Study getStudyObject () {
177 // ------------------------------
180 public String getTitle() {
181 // ------------------------
182 return mystudy.getTitle();
184 public String getType () {
185 // ------------------------
186 return ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale()).getString("label.study");
188 public String getVersion () {
189 // ---------------------------
192 public boolean isStepEnabled () {
193 // -------------------------------
194 return urightstep.isEnabled();
197 // ==============================================================================================================================
199 // ==============================================================================================================================
201 public URL newTemplateBasedDocument (String typename, User author) {
202 // ------------------------------------------------------------------
203 String filename = typename + ".xml"; // Only XML templates are writeable
204 File template = new File(getRepositoryService().getTemplatePath() + filename);
205 if (!template.exists()) return null;
207 Session connex = Database.getSession();
208 Transaction transax = connex.beginTransaction();
210 File udir = getRepositoryService().getDownloadDirectory(author);
211 File credoc = new File(udir.getPath() + "/" + filename);
213 // Creation of the meta-document
214 Step step = getSelectedStep(); // Should we check if the given document type is compatible ?
215 DocumentType type = Document.selectType(typename);
216 Document.Properties dprop = new Document.Properties();
217 Document medoc = getStepService().createDocument(step, dprop.setType(type).setFormat("xml").setAuthor(author)).value();
220 // Instantiation of the template into the user download directory
221 if (!udir.exists()) udir.mkdir();
222 if (credoc.exists()) credoc.delete();
223 Do.copy(template, credoc);
225 // Transfer to the document of all known properties
226 ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
227 SimpleDateFormat get = new SimpleDateFormat(locale.getString("date.format"));
228 Writer tool = Toolbox.getWriter(credoc);
229 List<Step> slist = getInvolvedSteps();
230 for (Iterator<Step> i=slist.iterator(); i.hasNext(); ) {
231 List<SimulationContext> clist = i.next().getAllSimulationContexts();
232 for (Iterator<SimulationContext> j=clist.iterator(); j.hasNext(); ) {
233 SimulationContext context = j.next();
234 tool.updateProperty(context.getType().getName(), context.getValue());
237 tool.updateProperty("reference", medoc.getReference());
238 tool.updateProperty("study", mystudy.getTitle());
239 tool.updateProperty("step", locale.getString("folder.step." + step.getNumber()).replaceAll("''", "'"));
240 tool.updateProperty("author", author.getUsername().toUpperCase());
241 tool.updateProperty("date", get.format(medoc.getCreationDate()));
242 tool.updateProperty("history", locale.getString("label.creation").replaceAll("''", "'"));
245 return new URL(ApplicationSettings.getDownloadURL(author) + filename);
247 catch (Exception saverror) {
248 logger.error("Reason:", saverror);
249 if (transax != null && transax.isActive()) {
250 // Second try-catch as the rollback could fail as well
253 } catch (HibernateException backerror) {
254 logger.debug("Error rolling back transaction", backerror);
261 public void selectDocument (String docurl) {
262 // ------------------------------------------
263 String prefix = ApplicationSettings.getRepositoryURL();
265 if (docurl.startsWith(prefix)) try {
266 Session connex = Database.getSession();
267 Transaction transax = connex.beginTransaction();
268 String path = docurl.substring(prefix.length());
269 String[] parse = path.split("'");
272 for (int i=1; i<parse.length; i++) path = path + "''" + parse[i];
273 // Better call Database.selectDocument(path), but this service does not exist (overloading issue)
274 String query = "from Document where path='" + path + "'";
275 Document value = (Document)Database.getSession().createQuery(query).uniqueResult();
277 selecdoc = ustep.getDocument(value.getIndex());
280 catch (Exception error) {
281 logger.error("Reason:", error);
285 public void setSelection (String step) {
286 // --------------------------------------
287 if (!step.equals(selection)) {
290 setupPreviousToSelectedSteps();
291 updateSimulationContexts(); // Initializes contexts according to the selected steps
293 ustep = involving.get(involving.size()-1);
294 urightstep = new StepRights(cuser, ustep);
295 ustep.setActor(cuser);
296 menu.selects(selection); // Updates menu items to be displayed
297 setupContents(); // The contents may have changed even if the selection is the same
300 // ==============================================================================================================================
301 // Protected services
302 // ==============================================================================================================================
304 protected void add (Publication doc) {
305 // ------------------------------------
306 DocumentFacade facade = new DocumentFacade(this, doc, getProjectSettings(), getPublicationService());
307 boolean first = (contents.size() == 0);
309 docpres.put(doc.getIndex(), facade);
310 contents.add(0, facade); // Prepend the new publication
311 if (first) this.getMenu().refreshSelectedItem();
315 protected void add (SimulationContext contex) {
316 // ---------------------------------------------
317 SimulationContextFacade facade = new SimulationContextFacade(contex, getProjectSettings().getAllSteps());
322 protected void add (KnowledgeElement kelm) {
323 // ------------------------------------------
324 KnowledgeElementFacade facade = new KnowledgeElementFacade(kelm);
325 //RKV KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
326 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
327 //RKV:Begin: Find a knowledge iterator for appropriate knowledge type
328 KnowledgeIterator known = null;
329 for (KnowledgeIterator aKnowledgeSection : knowledge) {
330 if (aKnowledgeSection.getIndex().equals(String.valueOf(kelm.getType().getIndex()))) {
331 known = aKnowledgeSection;
335 if (known != null) { //RKV:End
336 knowpres.put(kelm.getIndex(), facade);
337 known.list.add(facade); // Insert the new knowledge at the end of the corresponding knowledge type
341 protected void remove (Publication doctag) {
342 // ------------------------------------------
343 for (Iterator<DocumentFacade> i=contents.iterator(); i.hasNext(); ) {
344 DocumentFacade facade = i.next();
345 if (!facade.isFacadeOf(doctag)) continue;
349 if (contents.size() == 0) this.getMenu().refreshSelectedItem();
352 protected void changeUser (User user) {
353 // -------------------------------------
356 if (mystudy.isStaffedBy(cuser)) {
357 popup = ApplicationSettings.getPopupMenu("steditable");
358 popup.setContext("study", new StudyRights(cuser, mystudy));
360 ustep.setActor(cuser);
361 urightstudy = new StudyRights(cuser, mystudy);
362 urightstep = new StepRights(cuser, ustep);
365 protected void remove (SimulationContext contex) {
366 // ------------------------------------------------
367 for (Iterator<SimulationContextFacade> i=context.iterator(); i.hasNext(); ) {
368 SimulationContextFacade facade = i.next();
369 if (!facade.isFacadeOf(contex)) continue;
375 protected void remove (KnowledgeElement kelm) {
376 // ---------------------------------------------
377 KnowledgeIterator known = knowledge.get((int)(kelm.getType().getIndex() - 2));
378 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
379 knowpres.remove(kelm.getIndex());
380 for (Iterator<KnowledgeElementFacade> i=known.list.iterator(); i.hasNext(); ) {
381 KnowledgeElementFacade facade = i.next();
382 if (!facade.isFacadeOf(kelm)) continue;
388 protected void update (Publication doc) {
389 // ---------------------------------------
390 DocumentFacade facade = docpres.get(doc.getIndex());
391 if (facade != null) {
396 protected void update (KnowledgeElement kelm) {
397 // ---------------------------------------------
398 KnowledgeElementFacade facade = knowpres.get(kelm.getIndex());
399 if (facade != null) {
404 protected void updateSimulationContexts () {
405 // ------------------------------------------
407 for (Iterator<Step> i=involving.iterator(); i.hasNext(); ) {
408 for (Iterator<SimulationContext> j=i.next().getAllSimulationContexts().iterator(); j.hasNext(); ) {
409 context.add( new SimulationContextFacade(j.next(), getProjectSettings().getAllSteps()) );
414 // ==============================================================================================================================
416 // ==============================================================================================================================
418 private void setupPreviousToSelectedSteps () {
419 // --------------------------------------------
420 String[] item = selection.split("\\x2E");
421 int major = Integer.valueOf(item[0]);
422 int minor = Integer.valueOf(item[1]);
428 Scenario[] branch = mystudy.getScenarii();
429 Scenario scenar = branch[0];
430 for (int i=0; i<branch.length; i++) {
432 if (scenar.getIndex() == major) break; // Supposed exist
434 step = getProjectElementService().getSteps(scenar);
435 base = step[0].getNumber() - 1;
436 for (int i=0; i+base<minor; i++) {
437 involving.add(step[i]);
440 step = getProjectElementService().getSteps(mystudy);
441 for (int i=step.length-1; i>-1; i--) {
442 Step firstep = step[i];
443 if(firstep.getNumber() > base) continue;
444 involving.add(0, firstep);
449 * Get the projectElementService.
451 * @return the projectElementService
453 public ProjectElementService getProjectElementService() {
454 return _projectElementService;
458 * Set the projectElementService.
460 * @param projectElementService
461 * the projectElementService to set
463 public void setProjectElementService(
464 ProjectElementService projectElementService) {
465 _projectElementService = projectElementService;
469 * Get the scenarioService.
471 * @return the scenarioService
473 public ScenarioService getScenarioService() {
474 return _scenarioService;
478 * Set the scenarioService.
480 * @param scenarioService
481 * the scenarioService to set
483 public void setScenarioService(ScenarioService scenarioService) {
484 _scenarioService = scenarioService;
488 * Get the stepService.
489 * @return the stepService
491 public StepService getStepService() {
496 * Set the stepService.
497 * @param stepService the stepService to set
499 public void setStepService(StepService stepService) {
500 _stepService = stepService;
504 * Get the repositoryService.
505 * @return the repositoryService
507 public RepositoryService getRepositoryService() {
508 return _repositoryService;
512 * Set the repositoryService.
513 * @param repositoryService the repositoryService to set
515 public void setRepositoryService(RepositoryService repositoryService) {
516 _repositoryService = repositoryService;