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.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 project element service.
61 private ProjectElementService _projectElementService;
63 * Injected scenario service.
65 private ScenarioService _scenarioService;
67 * Injected step service.
69 private StepService _stepService;
71 * Injected repository service.
73 private RepositoryService _repositoryService;
74 // ==============================================================================================================================
76 // ==============================================================================================================================
79 * Open the given study in the current http session.
80 * @param user the current user
81 * @param study the study to open
82 * @return this open study object
84 public OpenStudy open (User user, Study study) {
85 // -----------------------------------------
86 ResourceBundle custom = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
87 SimpleDateFormat datstring = new SimpleDateFormat(custom.getString("date.format"));
88 Revision.Format verstring = new Revision.Format(getProjectSettings().getRevisionPattern());
90 cuser = user; // May be null if nobody connected
92 selection = "0.1"; // Default selection
95 // Preparation of the display
96 version = verstring.format(mystudy.getVersion());
97 credate = datstring.format(mystudy.getDate());
98 lasdate = ""; // Not yet supported
99 description = mystudy.getDescription();
100 involving = new ArrayList<Step>(1);
101 context = new ArrayList<SimulationContextFacade>();
102 ustep = getProjectElementService().getFirstStep(mystudy);
103 ustep.setActor(cuser);
104 involving.add(ustep);
105 for (Iterator<SimulationContext> i=ustep.getAllSimulationContexts().iterator(); i.hasNext(); ) {
106 context.add( new SimulationContextFacade(i.next(), getProjectSettings().getAllSteps()) );
108 if (mystudy.isStaffedBy(cuser) || mystudy.hasActor(cuser)) {
109 // ProgressState state = mystudy.getProgressState();
110 // if (state == ProgressState.inCHECK) popup = ApplicationSettings.getPopupMenu("stapprovable");
111 // else if (state == ProgressState.APPROVED) popup = ApplicationSettings.getPopupMenu("stapproved");
112 /* else */ popup = ApplicationSettings.getPopupMenu("steditable");
113 popup.setContext("study", new StudyRights(cuser, mystudy));
115 urightstudy = new StudyRights(cuser, mystudy);
116 urightstep = new StepRights(cuser, ustep);
118 menu = new StudyMenu(mystudy);
119 ((StudyMenu)menu).setProjectElementService(getProjectElementService());
120 ((StudyMenu)menu).setScenarioService(getScenarioService());
121 menu.selects(selection); // Initializes menu items to be displayed
122 setupContents(); // Initializes documents and knowledge at ustep
126 // ==============================================================================================================================
128 // ==============================================================================================================================
130 public String getAuthorName() {
131 // -----------------------------
132 return mystudy.getAuthor().toString();
134 public Long getIndex() {
135 // -------------------------
136 return mystudy.getIndex();
138 public String getDate () {
139 // ------------------------
142 public StudyMenu getMenu () {
143 // ---------------------------
144 return (StudyMenu)menu;
146 public ProgressState getProgressState() {
147 // ----------------------------------------
148 return mystudy.getProgressState();
150 public String getLastModificationDate () {
151 // ----------------------------------------
154 public ToolBar getModuleBar () {
155 // ------------------------------
156 return ApplicationSettings.getMe().getModuleBar(getSelectedStep());
158 public String getReference() {
159 // ----------------------------
160 return mystudy.getReference();
162 public Publication getSelectedDocument () {
163 // -----------------------------------------
166 public StepRights getSelectedStepRights () {
167 // ------------------------------------------
170 public StudyRights getStudyRights () {
171 // ------------------------------------
174 public Study getStudyObject () {
175 // ------------------------------
178 public String getTitle() {
179 // ------------------------
180 return mystudy.getTitle();
182 public String getType () {
183 // ------------------------
184 return ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale()).getString("label.study");
186 public String getVersion () {
187 // ---------------------------
190 public boolean isStepEnabled () {
191 // -------------------------------
192 return urightstep.isEnabled();
195 // ==============================================================================================================================
197 // ==============================================================================================================================
199 public URL newTemplateBasedDocument (String typename, User author) {
200 // ------------------------------------------------------------------
201 String filename = typename + ".xml"; // Only XML templates are writeable
202 File template = new File(getRepositoryService().getTemplatePath() + filename);
203 if (!template.exists()) return null;
205 Session connex = Database.getSession();
206 Transaction transax = connex.beginTransaction();
208 File udir = getRepositoryService().getDownloadDirectory(author);
209 File credoc = new File(udir.getPath() + "/" + filename);
211 // Creation of the meta-document
212 Step step = getSelectedStep(); // Should we check if the given document type is compatible ?
213 DocumentType type = Document.selectType(typename);
214 Document.Properties dprop = new Document.Properties();
215 Document medoc = getStepService().createDocument(step, dprop.setType(type).setFormat("xml").setAuthor(author)).value();
218 // Instantiation of the template into the user download directory
219 if (!udir.exists()) udir.mkdir();
220 if (credoc.exists()) credoc.delete();
221 Do.copy(template, credoc);
223 // Transfer to the document of all known properties
224 ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
225 SimpleDateFormat get = new SimpleDateFormat(locale.getString("date.format"));
226 Writer tool = Toolbox.getWriter(credoc);
227 List<Step> slist = getInvolvedSteps();
228 for (Iterator<Step> i=slist.iterator(); i.hasNext(); ) {
229 List<SimulationContext> clist = i.next().getAllSimulationContexts();
230 for (Iterator<SimulationContext> j=clist.iterator(); j.hasNext(); ) {
231 SimulationContext context = j.next();
232 tool.updateProperty(context.getType().getName(), context.getValue());
235 tool.updateProperty("reference", medoc.getReference());
236 tool.updateProperty("study", mystudy.getTitle());
237 tool.updateProperty("step", locale.getString("folder.step." + step.getNumber()).replaceAll("''", "'"));
238 tool.updateProperty("author", author.getUsername().toUpperCase());
239 tool.updateProperty("date", get.format(medoc.getCreationDate()));
240 tool.updateProperty("history", locale.getString("label.creation").replaceAll("''", "'"));
243 return new URL(ApplicationSettings.getDownloadURL(author) + filename);
245 catch (Exception saverror) {
246 logger.error("Reason:", saverror);
247 if (transax != null && transax.isActive()) {
248 // Second try-catch as the rollback could fail as well
251 } catch (HibernateException backerror) {
252 logger.debug("Error rolling back transaction", backerror);
259 public void selectDocument (String docurl) {
260 // ------------------------------------------
261 String prefix = ApplicationSettings.getRepositoryURL();
263 if (docurl.startsWith(prefix)) try {
264 Session connex = Database.getSession();
265 Transaction transax = connex.beginTransaction();
266 String path = docurl.substring(prefix.length());
267 String[] parse = path.split("'");
270 for (int i=1; i<parse.length; i++) path = path + "''" + parse[i];
271 // Better call Database.selectDocument(path), but this service does not exist (overloading issue)
272 String query = "from Document where path='" + path + "'";
273 Document value = (Document)Database.getSession().createQuery(query).uniqueResult();
275 selecdoc = ustep.getDocument(value.getIndex());
278 catch (Exception error) {
279 logger.error("Reason:", error);
283 public void setSelection (String step) {
284 // --------------------------------------
285 if (!step.equals(selection)) {
288 setupPreviousToSelectedSteps();
289 updateSimulationContexts(); // Initializes contexts according to the selected steps
291 ustep = involving.get(involving.size()-1);
292 urightstep = new StepRights(cuser, ustep);
293 ustep.setActor(cuser);
294 menu.selects(selection); // Updates menu items to be displayed
295 setupContents(); // The contents may have changed even if the selection is the same
298 // ==============================================================================================================================
299 // Protected services
300 // ==============================================================================================================================
302 protected void add (Publication doc) {
303 // ------------------------------------
304 DocumentFacade facade = new DocumentFacade(this, doc, getProjectSettings(), getPublicationService());
305 boolean first = (contents.size() == 0);
307 docpres.put(doc.getIndex(), facade);
308 contents.add(0, facade); // Prepend the new publication
309 if (first) this.getMenu().refreshSelectedItem();
313 protected void add (SimulationContext contex) {
314 // ---------------------------------------------
315 SimulationContextFacade facade = new SimulationContextFacade(contex, getProjectSettings().getAllSteps());
320 protected void add (KnowledgeElement kelm) {
321 // ------------------------------------------
322 KnowledgeElementFacade facade = new KnowledgeElementFacade(kelm);
323 //RKV KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
324 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
325 //RKV:Begin: Find a knowledge iterator for appropriate knowledge type
326 KnowledgeIterator known = null;
327 for (KnowledgeIterator aKnowledgeSection : knowledge) {
328 if (aKnowledgeSection.getIndex().equals(String.valueOf(kelm.getType().getIndex()))) {
329 known = aKnowledgeSection;
333 if (known != null) { //RKV:End
334 knowpres.put(kelm.getIndex(), facade);
335 known.list.add(facade); // Insert the new knowledge at the end of the corresponding knowledge type
339 protected void remove (Publication doctag) {
340 // ------------------------------------------
341 for (Iterator<DocumentFacade> i=contents.iterator(); i.hasNext(); ) {
342 DocumentFacade facade = i.next();
343 if (!facade.isFacadeOf(doctag)) continue;
347 if (contents.size() == 0) this.getMenu().refreshSelectedItem();
350 protected void changeUser (User user) {
351 // -------------------------------------
354 if (mystudy.isStaffedBy(cuser)) {
355 popup = ApplicationSettings.getPopupMenu("steditable");
356 popup.setContext("study", new StudyRights(cuser, mystudy));
358 ustep.setActor(cuser);
359 urightstudy = new StudyRights(cuser, mystudy);
360 urightstep = new StepRights(cuser, ustep);
363 protected void remove (SimulationContext contex) {
364 // ------------------------------------------------
365 for (Iterator<SimulationContextFacade> i=context.iterator(); i.hasNext(); ) {
366 SimulationContextFacade facade = i.next();
367 if (!facade.isFacadeOf(contex)) continue;
373 protected void remove (KnowledgeElement kelm) {
374 // ---------------------------------------------
375 KnowledgeIterator known = knowledge.get((int)(kelm.getType().getIndex() - 2));
376 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
377 knowpres.remove(kelm.getIndex());
378 for (Iterator<KnowledgeElementFacade> i=known.list.iterator(); i.hasNext(); ) {
379 KnowledgeElementFacade facade = i.next();
380 if (!facade.isFacadeOf(kelm)) continue;
386 protected void update (Publication doc) {
387 // ---------------------------------------
388 DocumentFacade facade = docpres.get(doc.getIndex());
389 if (facade != null) {
394 protected void update (KnowledgeElement kelm) {
395 // ---------------------------------------------
396 KnowledgeElementFacade facade = knowpres.get(kelm.getIndex());
397 if (facade != null) {
402 protected void updateSimulationContexts () {
403 // ------------------------------------------
405 for (Iterator<Step> i=involving.iterator(); i.hasNext(); ) {
406 for (Iterator<SimulationContext> j=i.next().getAllSimulationContexts().iterator(); j.hasNext(); ) {
407 context.add( new SimulationContextFacade(j.next(), getProjectSettings().getAllSteps()) );
412 // ==============================================================================================================================
414 // ==============================================================================================================================
416 private void setupPreviousToSelectedSteps () {
417 // --------------------------------------------
418 String[] item = selection.split("\\x2E");
419 int major = Integer.valueOf(item[0]);
420 int minor = Integer.valueOf(item[1]);
426 Scenario[] branch = mystudy.getScenarii();
427 Scenario scenar = branch[0];
428 for (int i=0; i<branch.length; i++) {
430 if (scenar.getIndex() == major) break; // Supposed exist
432 step = getProjectElementService().getSteps(scenar);
433 base = step[0].getNumber() - 1;
434 for (int i=0; i+base<minor; i++) {
435 involving.add(step[i]);
438 step = getProjectElementService().getSteps(mystudy);
439 for (int i=step.length-1; i>-1; i--) {
440 Step firstep = step[i];
441 if(firstep.getNumber() > base) continue;
442 involving.add(0, firstep);
447 * Get the projectElementService.
449 * @return the projectElementService
451 public ProjectElementService getProjectElementService() {
452 return _projectElementService;
456 * Set the projectElementService.
458 * @param projectElementService
459 * the projectElementService to set
461 public void setProjectElementService(
462 ProjectElementService projectElementService) {
463 _projectElementService = projectElementService;
467 * Get the scenarioService.
469 * @return the scenarioService
471 public ScenarioService getScenarioService() {
472 return _scenarioService;
476 * Set the scenarioService.
478 * @param scenarioService
479 * the scenarioService to set
481 public void setScenarioService(ScenarioService scenarioService) {
482 _scenarioService = scenarioService;
486 * Get the stepService.
487 * @return the stepService
489 public StepService getStepService() {
494 * Set the stepService.
495 * @param stepService the stepService to set
497 public void setStepService(StepService stepService) {
498 _stepService = stepService;
502 * Get the repositoryService.
503 * @return the repositoryService
505 public RepositoryService getRepositoryService() {
506 return _repositoryService;
510 * Set the repositoryService.
511 * @param repositoryService the repositoryService to set
513 public void setRepositoryService(RepositoryService repositoryService) {
514 _repositoryService = repositoryService;