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.PublicationService;
31 import org.splat.service.ScenarioService;
32 import org.splat.service.StepService;
33 import org.splat.service.technical.ProjectSettingsService;
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;
45 public class OpenStudy extends OpenObject implements OpenStudyServices {
47 private Study mystudy;
48 private StudyRights urightstudy; // User rights on the open study
49 private StepRights urightstep; // User rights on the selected step
50 private String version;
51 private String credate;
52 private String lasdate;
53 private Publication selecdoc;
54 private ProjectElementService _projectElementService;
55 private ScenarioService _scenarioService;
56 private StepService _stepService;
57 protected final static Logger logger = org.splat.simer.Action.logger;
59 // ==============================================================================================================================
61 // ==============================================================================================================================
63 public OpenStudy open (User user, Study study) {
64 // -----------------------------------------
65 ResourceBundle custom = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
66 SimpleDateFormat datstring = new SimpleDateFormat(custom.getString("date.format"));
67 Revision.Format verstring = new Revision.Format(getProjectSettings().getRevisionPattern());
69 cuser = user; // May be null if nobody connected
71 selection = "0.1"; // Default selection
74 // Preparation of the display
75 version = verstring.format(mystudy.getVersion());
76 credate = datstring.format(mystudy.getDate());
77 lasdate = ""; // Not yet supported
78 description = mystudy.getDescription();
79 involving = new ArrayList<Step>(1);
80 context = new ArrayList<SimulationContextFacade>();
81 ustep = getProjectElementService().getFirstStep(mystudy);
82 ustep.setActor(cuser);
84 for (Iterator<SimulationContext> i=ustep.getAllSimulationContexts().iterator(); i.hasNext(); ) {
85 context.add( new SimulationContextFacade(i.next(), getProjectSettings().getAllSteps()) );
87 if (mystudy.isStaffedBy(cuser) || mystudy.hasActor(cuser)) {
88 // ProgressState state = mystudy.getProgressState();
89 // if (state == ProgressState.inCHECK) popup = ApplicationSettings.getPopupMenu("stapprovable");
90 // else if (state == ProgressState.APPROVED) popup = ApplicationSettings.getPopupMenu("stapproved");
91 /* else */ popup = ApplicationSettings.getPopupMenu("steditable");
92 popup.setContext("study", new StudyRights(cuser, mystudy));
94 urightstudy = new StudyRights(cuser, mystudy);
95 urightstep = new StepRights(cuser, ustep);
97 menu = new StudyMenu(mystudy);
98 ((StudyMenu)menu).setProjectElementService(getProjectElementService());
99 ((StudyMenu)menu).setScenarioService(getScenarioService());
100 menu.selects(selection); // Initializes menu items to be displayed
101 setupContents(); // Initializes documents and knowledge at ustep
105 // ==============================================================================================================================
107 // ==============================================================================================================================
109 public String getAuthorName() {
110 // -----------------------------
111 return mystudy.getAuthor().toString();
113 public Long getIndex() {
114 // -------------------------
115 return mystudy.getIndex();
117 public String getDate () {
118 // ------------------------
121 public StudyMenu getMenu () {
122 // ---------------------------
123 return (StudyMenu)menu;
125 public ProgressState getProgressState() {
126 // ----------------------------------------
127 return mystudy.getProgressState();
129 public String getLastModificationDate () {
130 // ----------------------------------------
133 public ToolBar getModuleBar () {
134 // ------------------------------
135 return ApplicationSettings.getMe().getModuleBar(getSelectedStep());
137 public String getReference() {
138 // ----------------------------
139 return mystudy.getReference();
141 public Publication getSelectedDocument () {
142 // -----------------------------------------
145 public StepRights getSelectedStepRights () {
146 // ------------------------------------------
149 public StudyRights getStudyRights () {
150 // ------------------------------------
153 public Study getStudyObject () {
154 // ------------------------------
157 public String getTitle() {
158 // ------------------------
159 return mystudy.getTitle();
161 public String getType () {
162 // ------------------------
163 return ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale()).getString("label.study");
165 public String getVersion () {
166 // ---------------------------
169 public boolean isStepEnabled () {
170 // -------------------------------
171 return urightstep.isEnabled();
174 // ==============================================================================================================================
176 // ==============================================================================================================================
178 public URL newTemplateBasedDocument (String typename, User author) {
179 // ------------------------------------------------------------------
180 String filename = typename + ".xml"; // Only XML templates are writeable
181 File template = new File(Database.getTemplatePath() + filename);
182 if (!template.exists()) return null;
184 Session connex = Database.getSession();
185 Transaction transax = connex.beginTransaction();
187 File udir = Database.getDownloadDirectory(author);
188 File credoc = new File(udir.getPath() + "/" + filename);
190 // Creation of the meta-document
191 Step step = getSelectedStep(); // Should we check if the given document type is compatible ?
192 DocumentType type = Document.selectType(typename);
193 Document.Properties dprop = new Document.Properties();
194 Document medoc = getStepService().createDocument(step, dprop.setType(type).setFormat("xml").setAuthor(author)).value();
197 // Instantiation of the template into the user download directory
198 if (!udir.exists()) udir.mkdir();
199 if (credoc.exists()) credoc.delete();
200 Do.copy(template, credoc);
202 // Transfer to the document of all known properties
203 ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
204 SimpleDateFormat get = new SimpleDateFormat(locale.getString("date.format"));
205 Writer tool = Toolbox.getWriter(credoc);
206 List<Step> slist = getInvolvedSteps();
207 for (Iterator<Step> i=slist.iterator(); i.hasNext(); ) {
208 List<SimulationContext> clist = i.next().getAllSimulationContexts();
209 for (Iterator<SimulationContext> j=clist.iterator(); j.hasNext(); ) {
210 SimulationContext context = j.next();
211 tool.updateProperty(context.getType().getName(), context.getValue());
214 tool.updateProperty("reference", medoc.getReference());
215 tool.updateProperty("study", mystudy.getTitle());
216 tool.updateProperty("step", locale.getString("folder.step." + step.getNumber()).replaceAll("''", "'"));
217 tool.updateProperty("author", author.getUsername().toUpperCase());
218 tool.updateProperty("date", get.format(medoc.getCreationDate()));
219 tool.updateProperty("history", locale.getString("label.creation").replaceAll("''", "'"));
222 return new URL(ApplicationSettings.getDownloadURL(author) + filename);
224 catch (Exception saverror) {
225 logger.error("Reason:", saverror);
226 if (transax != null && transax.isActive()) {
227 // Second try-catch as the rollback could fail as well
230 } catch (HibernateException backerror) {
231 logger.debug("Error rolling back transaction", backerror);
238 public void selectDocument (String docurl) {
239 // ------------------------------------------
240 String prefix = ApplicationSettings.getRepositoryURL();
242 if (docurl.startsWith(prefix)) try {
243 Session connex = Database.getSession();
244 Transaction transax = connex.beginTransaction();
245 String path = docurl.substring(prefix.length());
246 String[] parse = path.split("'");
249 for (int i=1; i<parse.length; i++) path = path + "''" + parse[i];
250 // Better call Database.selectDocument(path), but this service does not exist (overloading issue)
251 String query = "from Document where path='" + path + "'";
252 Document value = (Document)Database.getSession().createQuery(query).uniqueResult();
254 selecdoc = ustep.getDocument(value.getIndex());
257 catch (Exception error) {
258 logger.error("Reason:", error);
262 public void setSelection (String step) {
263 // --------------------------------------
264 if (!step.equals(selection)) {
267 setupPreviousToSelectedSteps();
268 updateSimulationContexts(); // Initializes contexts according to the selected steps
270 ustep = involving.get(involving.size()-1);
271 urightstep = new StepRights(cuser, ustep);
272 ustep.setActor(cuser);
273 menu.selects(selection); // Updates menu items to be displayed
274 setupContents(); // The contents may have changed even if the selection is the same
277 // ==============================================================================================================================
278 // Protected services
279 // ==============================================================================================================================
281 protected void add (Publication doc) {
282 // ------------------------------------
283 DocumentFacade facade = new DocumentFacade(this, doc, getProjectSettings(), getPublicationService());
284 boolean first = (contents.size() == 0);
286 docpres.put(doc.getIndex(), facade);
287 contents.add(0, facade); // Prepend the new publication
288 if (first) this.getMenu().refreshSelectedItem();
292 protected void add (SimulationContext contex) {
293 // ---------------------------------------------
294 SimulationContextFacade facade = new SimulationContextFacade(contex, getProjectSettings().getAllSteps());
299 protected void add (KnowledgeElement kelm) {
300 // ------------------------------------------
301 KnowledgeElementFacade facade = new KnowledgeElementFacade(kelm);
302 //RKV KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
303 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
304 //RKV:Begin: Find a knowledge iterator for appropriate knowledge type
305 KnowledgeIterator known = null;
306 for (KnowledgeIterator aKnowledgeSection : knowledge) {
307 if (aKnowledgeSection.getIndex().equals(String.valueOf(kelm.getType().getIndex()))) {
308 known = aKnowledgeSection;
312 if (known != null) { //RKV:End
313 knowpres.put(kelm.getIndex(), facade);
314 known.list.add(facade); // Insert the new knowledge at the end of the corresponding knowledge type
318 protected void remove (Publication doctag) {
319 // ------------------------------------------
320 for (Iterator<DocumentFacade> i=contents.iterator(); i.hasNext(); ) {
321 DocumentFacade facade = i.next();
322 if (!facade.isFacadeOf(doctag)) continue;
326 if (contents.size() == 0) this.getMenu().refreshSelectedItem();
329 protected void changeUser (User user) {
330 // -------------------------------------
333 if (mystudy.isStaffedBy(cuser)) {
334 popup = ApplicationSettings.getPopupMenu("steditable");
335 popup.setContext("study", new StudyRights(cuser, mystudy));
337 ustep.setActor(cuser);
338 urightstudy = new StudyRights(cuser, mystudy);
339 urightstep = new StepRights(cuser, ustep);
342 protected void remove (SimulationContext contex) {
343 // ------------------------------------------------
344 for (Iterator<SimulationContextFacade> i=context.iterator(); i.hasNext(); ) {
345 SimulationContextFacade facade = i.next();
346 if (!facade.isFacadeOf(contex)) continue;
352 protected void remove (KnowledgeElement kelm) {
353 // ---------------------------------------------
354 KnowledgeIterator known = knowledge.get((int)(kelm.getType().getIndex() - 2));
355 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
356 knowpres.remove(kelm.getIndex());
357 for (Iterator<KnowledgeElementFacade> i=known.list.iterator(); i.hasNext(); ) {
358 KnowledgeElementFacade facade = i.next();
359 if (!facade.isFacadeOf(kelm)) continue;
365 protected void update (Publication doc) {
366 // ---------------------------------------
367 DocumentFacade facade = docpres.get(doc.getIndex());
368 if (facade != null) {
373 protected void update (KnowledgeElement kelm) {
374 // ---------------------------------------------
375 KnowledgeElementFacade facade = knowpres.get(kelm.getIndex());
376 if (facade != null) {
381 protected void updateSimulationContexts () {
382 // ------------------------------------------
384 for (Iterator<Step> i=involving.iterator(); i.hasNext(); ) {
385 for (Iterator<SimulationContext> j=i.next().getAllSimulationContexts().iterator(); j.hasNext(); ) {
386 context.add( new SimulationContextFacade(j.next(), getProjectSettings().getAllSteps()) );
391 // ==============================================================================================================================
393 // ==============================================================================================================================
395 private void setupPreviousToSelectedSteps () {
396 // --------------------------------------------
397 String[] item = selection.split("\\x2E");
398 int major = Integer.valueOf(item[0]);
399 int minor = Integer.valueOf(item[1]);
405 Scenario[] branch = mystudy.getScenarii();
406 Scenario scenar = branch[0];
407 for (int i=0; i<branch.length; i++) {
409 if (scenar.getIndex() == major) break; // Supposed exist
411 step = getProjectElementService().getSteps(scenar);
412 base = step[0].getNumber() - 1;
413 for (int i=0; i+base<minor; i++) {
414 involving.add(step[i]);
417 step = getProjectElementService().getSteps(mystudy);
418 for (int i=step.length-1; i>-1; i--) {
419 Step firstep = step[i];
420 if(firstep.getNumber() > base) continue;
421 involving.add(0, firstep);
426 * Get the projectElementService.
428 * @return the projectElementService
430 public ProjectElementService getProjectElementService() {
431 return _projectElementService;
435 * Set the projectElementService.
437 * @param projectElementService
438 * the projectElementService to set
440 public void setProjectElementService(
441 ProjectElementService projectElementService) {
442 _projectElementService = projectElementService;
446 * Get the scenarioService.
448 * @return the scenarioService
450 public ScenarioService getScenarioService() {
451 return _scenarioService;
455 * Set the scenarioService.
457 * @param scenarioService
458 * the scenarioService to set
460 public void setScenarioService(ScenarioService scenarioService) {
461 _scenarioService = scenarioService;
465 * Get the stepService.
466 * @return the stepService
468 public StepService getStepService() {
473 * Set the stepService.
474 * @param stepService the stepService to set
476 public void setStepService(StepService stepService) {
477 _stepService = stepService;