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.kernel.User;
22 import org.splat.manox.Toolbox;
23 import org.splat.manox.Writer;
24 import org.splat.som.Database;
25 import org.splat.som.Document;
26 import org.splat.som.DocumentType;
27 import org.splat.som.KnowledgeElement;
28 import org.splat.som.ProgressState;
29 import org.splat.som.ProjectSettings;
30 import org.splat.som.Publication;
31 import org.splat.som.Revision;
32 import org.splat.som.Scenario;
33 import org.splat.som.SimulationContext;
34 import org.splat.som.Step;
35 import org.splat.som.StepRights;
36 import org.splat.som.Study;
37 import org.splat.som.StudyRights;
38 import org.splat.wapp.ToolBar;
41 public class OpenStudy extends OpenObject implements OpenStudyServices {
43 private Study mystudy;
44 private StudyRights urightstudy; // User rights on the open study
45 private StepRights urightstep; // User rights on the selected step
46 private String version;
47 private String credate;
48 private String lasdate;
49 private Publication selecdoc;
51 protected final static Logger logger = org.splat.simer.Action.logger;
53 // ==============================================================================================================================
55 // ==============================================================================================================================
57 public OpenStudy (User user, Study study) {
58 // -----------------------------------------
59 ResourceBundle custom = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
60 SimpleDateFormat datstring = new SimpleDateFormat(custom.getString("date.format"));
61 Revision.Format verstring = new Revision.Format(ProjectSettings.getRevisionPattern());
63 cuser = user; // May be null if nobody connected
65 selection = "0.1"; // Default selection
68 // Preparation of the display
69 version = verstring.format(mystudy.getVersion());
70 credate = datstring.format(mystudy.getDate());
71 lasdate = ""; // Not yet supported
72 description = mystudy.getDescription();
73 involving = new ArrayList<Step>(1);
74 context = new ArrayList<SimulationContextFacade>();
75 ustep = mystudy.getFirstStep();
76 ustep.setActor(cuser);
78 for (Iterator<SimulationContext> i=ustep.getAllSimulationContexts().iterator(); i.hasNext(); ) {
79 context.add( new SimulationContextFacade(i.next()) );
81 if (mystudy.isStaffedBy(cuser) || mystudy.hasActor(cuser)) {
82 // ProgressState state = mystudy.getProgressState();
83 // if (state == ProgressState.inCHECK) popup = ApplicationSettings.getPopupMenu("stapprovable");
84 // else if (state == ProgressState.APPROVED) popup = ApplicationSettings.getPopupMenu("stapproved");
85 /* else */ popup = ApplicationSettings.getPopupMenu("steditable");
86 popup.setContext("study", new StudyRights(cuser, mystudy));
88 urightstudy = new StudyRights(cuser, mystudy);
89 urightstep = new StepRights(cuser, ustep);
91 menu = new StudyMenu(mystudy);
92 menu.selects(selection); // Initializes menu items to be displayed
93 setupContents(); // Initializes documents and knowledge at ustep
96 // ==============================================================================================================================
98 // ==============================================================================================================================
100 public String getAuthorName() {
101 // -----------------------------
102 return mystudy.getAuthor().toString();
104 public Integer getIndex() {
105 // -------------------------
106 return mystudy.getIndex();
108 public String getDate () {
109 // ------------------------
112 public StudyMenu getMenu () {
113 // ---------------------------
114 return (StudyMenu)menu;
116 public ProgressState getProgressState() {
117 // ----------------------------------------
118 return mystudy.getProgressState();
120 public String getLastModificationDate () {
121 // ----------------------------------------
124 public ToolBar getModuleBar () {
125 // ------------------------------
126 return ApplicationSettings.getMe().getModuleBar(getSelectedStep());
128 public String getReference() {
129 // ----------------------------
130 return mystudy.getReference();
132 public Publication getSelectedDocument () {
133 // -----------------------------------------
136 public StepRights getSelectedStepRights () {
137 // ------------------------------------------
140 public StudyRights getStudyRights () {
141 // ------------------------------------
144 public Study getStudyObject () {
145 // ------------------------------
148 public String getTitle() {
149 // ------------------------
150 return mystudy.getTitle();
152 public String getType () {
153 // ------------------------
154 return ResourceBundle.getBundle("labels", ApplicationSettings.getCurrentLocale()).getString("label.study");
156 public String getVersion () {
157 // ---------------------------
160 public boolean isStepEnabled () {
161 // -------------------------------
162 return urightstep.isEnabled();
165 // ==============================================================================================================================
167 // ==============================================================================================================================
169 public URL newTemplateBasedDocument (String typename, User author) {
170 // ------------------------------------------------------------------
171 String filename = typename + ".xml"; // Only XML templates are writeable
172 File template = new File(Database.getTemplatePath() + filename);
173 if (!template.exists()) return null;
175 Session connex = Database.getSession();
176 Transaction transax = connex.beginTransaction();
178 File udir = Database.getDownloadDirectory(author);
179 File credoc = new File(udir.getPath() + "/" + filename);
181 // Creation of the meta-document
182 Step step = getSelectedStep(); // Should we check if the given document type is compatible ?
183 DocumentType type = Document.selectType(typename);
184 Document.Properties dprop = new Document.Properties();
185 Document medoc = step.createDocument(dprop.setType(type).setFormat("xml").setAuthor(author)).value();
188 // Instantiation of the template into the user download directory
189 if (!udir.exists()) udir.mkdir();
190 if (credoc.exists()) credoc.delete();
191 Do.copy(template, credoc);
193 // Transfer to the document of all known properties
194 ResourceBundle locale = ResourceBundle.getBundle("som", ApplicationSettings.getCurrentLocale());
195 SimpleDateFormat get = new SimpleDateFormat(locale.getString("date.format"));
196 Writer tool = Toolbox.getWriter(credoc);
197 List<Step> slist = getInvolvedSteps();
198 for (Iterator<Step> i=slist.iterator(); i.hasNext(); ) {
199 List<SimulationContext> clist = i.next().getAllSimulationContexts();
200 for (Iterator<SimulationContext> j=clist.iterator(); j.hasNext(); ) {
201 SimulationContext context = j.next();
202 tool.updateProperty(context.getType().getName(), context.getValue());
205 tool.updateProperty("reference", medoc.getReference());
206 tool.updateProperty("study", mystudy.getTitle());
207 tool.updateProperty("step", locale.getString("folder.step." + step.getNumber()).replaceAll("''", "'"));
208 tool.updateProperty("author", author.getUsername().toUpperCase());
209 tool.updateProperty("date", get.format(medoc.getCreationDate()));
210 tool.updateProperty("history", locale.getString("label.creation").replaceAll("''", "'"));
213 return new URL(ApplicationSettings.getDownloadURL(author) + filename);
215 catch (Exception saverror) {
216 logger.error("Reason:", saverror);
217 if (transax != null && transax.isActive()) {
218 // Second try-catch as the rollback could fail as well
221 } catch (HibernateException backerror) {
222 logger.debug("Error rolling back transaction", backerror);
229 public void selectDocument (String docurl) {
230 // ------------------------------------------
231 String prefix = ApplicationSettings.getRepositoryURL();
233 if (docurl.startsWith(prefix)) try {
234 Session connex = Database.getSession();
235 Transaction transax = connex.beginTransaction();
236 String path = docurl.substring(prefix.length());
237 String[] parse = path.split("'");
240 for (int i=1; i<parse.length; i++) path = path + "''" + parse[i];
241 // Better call Database.selectDocument(path), but this service does not exist (overloading issue)
242 String query = "from Document where path='" + path + "'";
243 Document value = (Document)Database.getSession().createQuery(query).uniqueResult();
245 selecdoc = ustep.getDocument(value.getIndex());
248 catch (Exception error) {
249 logger.error("Reason:", error);
253 public void setSelection (String step) {
254 // --------------------------------------
255 if (!step.equals(selection)) {
258 setupPreviousToSelectedSteps();
259 updateSimulationContexts(); // Initializes contexts according to the selected steps
261 ustep = involving.get(involving.size()-1);
262 urightstep = new StepRights(cuser, ustep);
263 ustep.setActor(cuser);
264 menu.selects(selection); // Updates menu items to be displayed
265 setupContents(); // The contents may have changed even if the selection is the same
268 // ==============================================================================================================================
269 // Protected services
270 // ==============================================================================================================================
272 protected void add (Publication doc) {
273 // ------------------------------------
274 DocumentFacade facade = new DocumentFacade(this, doc);
275 boolean first = (contents.size() == 0);
277 docpres.put(doc.getIndex(), facade);
278 contents.add(0, facade); // Prepend the new publication
279 if (first) this.getMenu().refreshSelectedItem();
283 protected void add (SimulationContext contex) {
284 // ---------------------------------------------
285 SimulationContextFacade facade = new SimulationContextFacade(contex);
290 protected void add (KnowledgeElement kelm) {
291 // ------------------------------------------
292 KnowledgeElementFacade facade = new KnowledgeElementFacade(kelm);
293 KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
294 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
295 knowpres.put(kelm.getIndex(), facade);
296 known.list.add(facade); // Insert the new knowledge at the end of the corresponding knowledge type
299 protected void remove (Publication doctag) {
300 // ------------------------------------------
301 for (Iterator<DocumentFacade> i=contents.iterator(); i.hasNext(); ) {
302 DocumentFacade facade = i.next();
303 if (!facade.isFacadeOf(doctag)) continue;
307 if (contents.size() == 0) this.getMenu().refreshSelectedItem();
310 protected void changeUser (User user) {
311 // -------------------------------------
314 if (mystudy.isStaffedBy(cuser)) {
315 popup = ApplicationSettings.getPopupMenu("steditable");
316 popup.setContext("study", new StudyRights(cuser, mystudy));
318 ustep.setActor(cuser);
319 urightstudy = new StudyRights(cuser, mystudy);
320 urightstep = new StepRights(cuser, ustep);
323 protected void remove (SimulationContext contex) {
324 // ------------------------------------------------
325 for (Iterator<SimulationContextFacade> i=context.iterator(); i.hasNext(); ) {
326 SimulationContextFacade facade = i.next();
327 if (!facade.isFacadeOf(contex)) continue;
333 protected void remove (KnowledgeElement kelm) {
334 // ---------------------------------------------
335 KnowledgeIterator known = knowledge.get(kelm.getType().getIndex() - 2);
336 // Knowledges are ordered by type index, from 0 to n-1, the first one being reserved (reason for -2)
337 knowpres.remove(kelm.getIndex());
338 for (Iterator<KnowledgeElementFacade> i=known.list.iterator(); i.hasNext(); ) {
339 KnowledgeElementFacade facade = i.next();
340 if (!facade.isFacadeOf(kelm)) continue;
346 protected void update (Publication doc) {
347 // ---------------------------------------
348 DocumentFacade facade = docpres.get(doc.getIndex());
349 if (facade != null) {
354 protected void update (KnowledgeElement kelm) {
355 // ---------------------------------------------
356 KnowledgeElementFacade facade = knowpres.get(kelm.getIndex());
357 if (facade != null) {
362 protected void updateSimulationContexts () {
363 // ------------------------------------------
365 for (Iterator<Step> i=involving.iterator(); i.hasNext(); ) {
366 for (Iterator<SimulationContext> j=i.next().getAllSimulationContexts().iterator(); j.hasNext(); ) {
367 context.add( new SimulationContextFacade(j.next()) );
372 // ==============================================================================================================================
374 // ==============================================================================================================================
376 private void setupPreviousToSelectedSteps () {
377 // --------------------------------------------
378 String[] item = selection.split("\\x2E");
379 int major = Integer.valueOf(item[0]);
380 int minor = Integer.valueOf(item[1]);
386 Scenario[] branch = mystudy.getScenarii();
387 Scenario scenar = branch[0];
388 for (int i=0; i<branch.length; i++) {
390 if (scenar.getIndex() == major) break; // Supposed exist
392 step = scenar.getSteps();
393 base = step[0].getNumber() - 1;
394 for (int i=0; i+base<minor; i++) {
395 involving.add(step[i]);
398 step = mystudy.getSteps();
399 for (int i=step.length-1; i>-1; i--) {
400 Step firstep = step[i];
401 if(firstep.getNumber() > base) continue;
402 involving.add(0, firstep);