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.technical.ProjectSettingsService;
32 import org.splat.dal.bo.som.Publication;
33 import org.splat.som.Revision;
34 import org.splat.dal.bo.som.Scenario;
35 import org.splat.dal.bo.som.SimulationContext;
36 import org.splat.som.Step;
37 import org.splat.som.StepRights;
38 import org.splat.dal.bo.som.Study;
39 import org.splat.som.StudyRights;
40 import org.splat.wapp.ToolBar;
43 public class OpenStudy extends OpenObject implements OpenStudyServices {
45 private Study mystudy;
46 private StudyRights urightstudy; // User rights on the open study
47 private StepRights urightstep; // User rights on the selected step
48 private String version;
49 private String credate;
50 private String lasdate;
51 private Publication selecdoc;
52 private ProjectSettingsService _projectSettingsService;
53 private ProjectElementService _projectElementService;
54 private ScenarioService _scenarioService;
56 protected final static Logger logger = org.splat.simer.Action.logger;
58 // ==============================================================================================================================
60 // ==============================================================================================================================
62 public OpenStudy open (User user, Study study) {
63 // -----------------------------------------
64 ResourceBundle custom = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
65 SimpleDateFormat datstring = new SimpleDateFormat(custom.getString("date.format"));
66 Revision.Format verstring = new Revision.Format(getProjectSettings().getRevisionPattern());
68 cuser = user; // May be null if nobody connected
70 selection = "0.1"; // Default selection
73 // Preparation of the display
74 version = verstring.format(mystudy.getVersion());
75 credate = datstring.format(mystudy.getDate());
76 lasdate = ""; // Not yet supported
77 description = mystudy.getDescription();
78 involving = new ArrayList<Step>(1);
79 context = new ArrayList<SimulationContextFacade>();
80 ustep = getProjectElementService().getFirstStep(mystudy);
81 ustep.setActor(cuser);
83 for (Iterator<SimulationContext> i=ustep.getAllSimulationContexts().iterator(); i.hasNext(); ) {
84 context.add( new SimulationContextFacade(i.next(), getProjectSettings().getAllSteps()) );
86 if (mystudy.isStaffedBy(cuser) || mystudy.hasActor(cuser)) {
87 // ProgressState state = mystudy.getProgressState();
88 // if (state == ProgressState.inCHECK) popup = ApplicationSettings.getPopupMenu("stapprovable");
89 // else if (state == ProgressState.APPROVED) popup = ApplicationSettings.getPopupMenu("stapproved");
90 /* else */ popup = ApplicationSettings.getPopupMenu("steditable");
91 popup.setContext("study", new StudyRights(cuser, mystudy));
93 urightstudy = new StudyRights(cuser, mystudy);
94 urightstep = new StepRights(cuser, ustep);
96 menu = new StudyMenu(mystudy);
97 ((StudyMenu)menu).setProjectElementService(getProjectElementService());
98 ((StudyMenu)menu).setScenarioService(getScenarioService());
99 menu.selects(selection); // Initializes menu items to be displayed
100 setupContents(); // Initializes documents and knowledge at ustep
104 // ==============================================================================================================================
106 // ==============================================================================================================================
108 public String getAuthorName() {
109 // -----------------------------
110 return mystudy.getAuthor().toString();
112 public Integer getIndex() {
113 // -------------------------
114 return mystudy.getIndex();
116 public String getDate () {
117 // ------------------------
120 public StudyMenu getMenu () {
121 // ---------------------------
122 return (StudyMenu)menu;
124 public ProgressState getProgressState() {
125 // ----------------------------------------
126 return mystudy.getProgressState();
128 public String getLastModificationDate () {
129 // ----------------------------------------
132 public ToolBar getModuleBar () {
133 // ------------------------------
134 return ApplicationSettings.getMe().getModuleBar(getSelectedStep());
136 public String getReference() {
137 // ----------------------------
138 return mystudy.getReference();
140 public Publication getSelectedDocument () {
141 // -----------------------------------------
144 public StepRights getSelectedStepRights () {
145 // ------------------------------------------
148 public StudyRights getStudyRights () {
149 // ------------------------------------
152 public Study getStudyObject () {
153 // ------------------------------
156 public String getTitle() {
157 // ------------------------
158 return mystudy.getTitle();
160 public String getType () {
161 // ------------------------
162 return ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale()).getString("label.study");
164 public String getVersion () {
165 // ---------------------------
168 public boolean isStepEnabled () {
169 // -------------------------------
170 return urightstep.isEnabled();
173 // ==============================================================================================================================
175 // ==============================================================================================================================
177 public URL newTemplateBasedDocument (String typename, User author) {
178 // ------------------------------------------------------------------
179 String filename = typename + ".xml"; // Only XML templates are writeable
180 File template = new File(Database.getTemplatePath() + filename);
181 if (!template.exists()) return null;
183 Session connex = Database.getSession();
184 Transaction transax = connex.beginTransaction();
186 File udir = Database.getDownloadDirectory(author);
187 File credoc = new File(udir.getPath() + "/" + filename);
189 // Creation of the meta-document
190 Step step = getSelectedStep(); // Should we check if the given document type is compatible ?
191 DocumentType type = Document.selectType(typename);
192 Document.Properties dprop = new Document.Properties();
193 Document medoc = step.createDocument(dprop.setType(type).setFormat("xml").setAuthor(author)).value();
196 // Instantiation of the template into the user download directory
197 if (!udir.exists()) udir.mkdir();
198 if (credoc.exists()) credoc.delete();
199 Do.copy(template, credoc);
201 // Transfer to the document of all known properties
202 ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
203 SimpleDateFormat get = new SimpleDateFormat(locale.getString("date.format"));
204 Writer tool = Toolbox.getWriter(credoc);
205 List<Step> slist = getInvolvedSteps();
206 for (Iterator<Step> i=slist.iterator(); i.hasNext(); ) {
207 List<SimulationContext> clist = i.next().getAllSimulationContexts();
208 for (Iterator<SimulationContext> j=clist.iterator(); j.hasNext(); ) {
209 SimulationContext context = j.next();
210 tool.updateProperty(context.getType().getName(), context.getValue());
213 tool.updateProperty("reference", medoc.getReference());
214 tool.updateProperty("study", mystudy.getTitle());
215 tool.updateProperty("step", locale.getString("folder.step." + step.getNumber()).replaceAll("''", "'"));
216 tool.updateProperty("author", author.getUsername().toUpperCase());
217 tool.updateProperty("date", get.format(medoc.getCreationDate()));
218 tool.updateProperty("history", locale.getString("label.creation").replaceAll("''", "'"));
221 return new URL(ApplicationSettings.getDownloadURL(author) + filename);
223 catch (Exception saverror) {
224 logger.error("Reason:", saverror);
225 if (transax != null && transax.isActive()) {
226 // Second try-catch as the rollback could fail as well
229 } catch (HibernateException backerror) {
230 logger.debug("Error rolling back transaction", backerror);
237 public void selectDocument (String docurl) {
238 // ------------------------------------------
239 String prefix = ApplicationSettings.getRepositoryURL();
241 if (docurl.startsWith(prefix)) try {
242 Session connex = Database.getSession();
243 Transaction transax = connex.beginTransaction();
244 String path = docurl.substring(prefix.length());
245 String[] parse = path.split("'");
248 for (int i=1; i<parse.length; i++) path = path + "''" + parse[i];
249 // Better call Database.selectDocument(path), but this service does not exist (overloading issue)
250 String query = "from Document where path='" + path + "'";
251 Document value = (Document)Database.getSession().createQuery(query).uniqueResult();
253 selecdoc = ustep.getDocument(value.getIndex());
256 catch (Exception error) {
257 logger.error("Reason:", error);
261 public void setSelection (String step) {
262 // --------------------------------------
263 if (!step.equals(selection)) {
266 setupPreviousToSelectedSteps();
267 updateSimulationContexts(); // Initializes contexts according to the selected steps
269 ustep = involving.get(involving.size()-1);
270 urightstep = new StepRights(cuser, ustep);
271 ustep.setActor(cuser);
272 menu.selects(selection); // Updates menu items to be displayed
273 setupContents(); // The contents may have changed even if the selection is the same
276 // ==============================================================================================================================
277 // Protected services
278 // ==============================================================================================================================
280 protected void add (Publication doc) {
281 // ------------------------------------
282 DocumentFacade facade = new DocumentFacade(this, doc);
283 boolean first = (contents.size() == 0);
285 docpres.put(doc.getIndex(), facade);
286 contents.add(0, facade); // Prepend the new publication
287 if (first) this.getMenu().refreshSelectedItem();
291 protected void add (SimulationContext contex) {
292 // ---------------------------------------------
293 SimulationContextFacade facade = new SimulationContextFacade(contex, getProjectSettings().getAllSteps());
298 protected void add (KnowledgeElement kelm) {
299 // ------------------------------------------
300 KnowledgeElementFacade facade = new KnowledgeElementFacade(kelm);
301 //RKV KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
302 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
303 //RKV:Begin: Find a knowledge iterator for appropriate knowledge type
304 KnowledgeIterator known = null;
305 for (KnowledgeIterator aKnowledgeSection : knowledge) {
306 if (aKnowledgeSection.getIndex().equals(String.valueOf(kelm.getType().getIndex()))) {
307 known = aKnowledgeSection;
311 if (known != null) { //RKV:End
312 knowpres.put(kelm.getIndex(), facade);
313 known.list.add(facade); // Insert the new knowledge at the end of the corresponding knowledge type
317 protected void remove (Publication doctag) {
318 // ------------------------------------------
319 for (Iterator<DocumentFacade> i=contents.iterator(); i.hasNext(); ) {
320 DocumentFacade facade = i.next();
321 if (!facade.isFacadeOf(doctag)) continue;
325 if (contents.size() == 0) this.getMenu().refreshSelectedItem();
328 protected void changeUser (User user) {
329 // -------------------------------------
332 if (mystudy.isStaffedBy(cuser)) {
333 popup = ApplicationSettings.getPopupMenu("steditable");
334 popup.setContext("study", new StudyRights(cuser, mystudy));
336 ustep.setActor(cuser);
337 urightstudy = new StudyRights(cuser, mystudy);
338 urightstep = new StepRights(cuser, ustep);
341 protected void remove (SimulationContext contex) {
342 // ------------------------------------------------
343 for (Iterator<SimulationContextFacade> i=context.iterator(); i.hasNext(); ) {
344 SimulationContextFacade facade = i.next();
345 if (!facade.isFacadeOf(contex)) continue;
351 protected void remove (KnowledgeElement kelm) {
352 // ---------------------------------------------
353 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 knowpres.remove(kelm.getIndex());
356 for (Iterator<KnowledgeElementFacade> i=known.list.iterator(); i.hasNext(); ) {
357 KnowledgeElementFacade facade = i.next();
358 if (!facade.isFacadeOf(kelm)) continue;
364 protected void update (Publication doc) {
365 // ---------------------------------------
366 DocumentFacade facade = docpres.get(doc.getIndex());
367 if (facade != null) {
372 protected void update (KnowledgeElement kelm) {
373 // ---------------------------------------------
374 KnowledgeElementFacade facade = knowpres.get(kelm.getIndex());
375 if (facade != null) {
380 protected void updateSimulationContexts () {
381 // ------------------------------------------
383 for (Iterator<Step> i=involving.iterator(); i.hasNext(); ) {
384 for (Iterator<SimulationContext> j=i.next().getAllSimulationContexts().iterator(); j.hasNext(); ) {
385 context.add( new SimulationContextFacade(j.next(), getProjectSettings().getAllSteps()) );
390 // ==============================================================================================================================
392 // ==============================================================================================================================
394 private void setupPreviousToSelectedSteps () {
395 // --------------------------------------------
396 String[] item = selection.split("\\x2E");
397 int major = Integer.valueOf(item[0]);
398 int minor = Integer.valueOf(item[1]);
404 Scenario[] branch = mystudy.getScenarii();
405 Scenario scenar = branch[0];
406 for (int i=0; i<branch.length; i++) {
408 if (scenar.getIndex() == major) break; // Supposed exist
410 step = getProjectElementService().getSteps(scenar);
411 base = step[0].getNumber() - 1;
412 for (int i=0; i+base<minor; i++) {
413 involving.add(step[i]);
416 step = getProjectElementService().getSteps(mystudy);
417 for (int i=step.length-1; i>-1; i--) {
418 Step firstep = step[i];
419 if(firstep.getNumber() > base) continue;
420 involving.add(0, firstep);
425 * Get project settings.
426 * @return Project settings service
428 private ProjectSettingsService getProjectSettings() {
429 return _projectSettingsService;
433 * Set project settings service.
434 * @param projectSettingsService project settings service
436 public void setProjectSettings(
437 ProjectSettingsService projectSettingsService) {
438 _projectSettingsService = projectSettingsService;
441 * Get the projectElementService.
443 * @return the projectElementService
445 public ProjectElementService getProjectElementService() {
446 return _projectElementService;
450 * Set the projectElementService.
452 * @param projectElementService
453 * the projectElementService to set
455 public void setProjectElementService(
456 ProjectElementService projectElementService) {
457 _projectElementService = projectElementService;
461 * Get the scenarioService.
463 * @return the scenarioService
465 public ScenarioService getScenarioService() {
466 return _scenarioService;
470 * Set the scenarioService.
472 * @param scenarioService
473 * the scenarioService to set
475 public void setScenarioService(ScenarioService scenarioService) {
476 _scenarioService = scenarioService;