1 package org.splat.service.technical;
5 * @author Daniel Brunier-Coulin
6 * @copyright OPEN CASCADE 2012
10 import java.io.FileNotFoundException;
11 import java.io.IOException;
12 import java.sql.SQLException;
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.Iterator;
16 import java.util.LinkedHashMap;
17 import java.util.List;
19 import java.util.Properties;
22 import javax.xml.parsers.DocumentBuilder;
23 import javax.xml.parsers.DocumentBuilderFactory;
25 import org.apache.log4j.Logger;
26 import org.splat.dal.bo.som.Document;
27 import org.splat.dal.bo.som.DocumentType;
28 import org.splat.dal.bo.som.KnowledgeElement;
29 import org.splat.dal.bo.som.KnowledgeElementType;
30 import org.splat.dal.bo.som.ProjectElement;
31 import org.splat.dal.bo.som.Scenario;
32 import org.splat.dal.bo.som.SimulationContextType;
33 import org.splat.dal.bo.som.Study;
34 import org.splat.dal.bo.som.ValidationCycle.Actor;
35 import org.splat.dal.dao.som.Database;
36 import org.splat.manox.XDOM;
37 import org.splat.service.DocumentTypeService;
38 import org.splat.service.KnowledgeElementTypeService;
39 import org.splat.service.SimulationContextTypeService;
40 import org.w3c.dom.Element;
41 import org.w3c.dom.NamedNodeMap;
42 import org.w3c.dom.Node;
43 import org.w3c.dom.NodeList;
46 * SIMAN workflow configuration data service.
48 public class ProjectSettingsServiceImpl implements ProjectSettingsService {
51 * The logger for the service.
53 protected final static Logger LOG = Logger
54 .getLogger(ProjectSettingsServiceImpl.class);
56 // Non persistent configuration information
58 * Repository settings.
60 private transient final Properties _reprop = new Properties();
62 * Pattern of study references.
64 private transient String _pattern;
66 * Scheme of file names stored into the repository.
68 private transient FileNaming _naming;
70 * Pattern of the presentation of version numbers.
72 private transient String _versioning;
74 * Ordered list of (transient) study steps.
76 private transient final List<ProjectSettingsService.Step> _steps = new ArrayList<ProjectSettingsService.Step>();
78 * Configuration document validation cycles.
80 private transient List<ProjectSettingsValidationCycle> _concycles;
82 // Temporary attributes initialized from the configuration file for populating the database with object types
84 * Document type names and uses mapping.
86 private transient Map<String, String> _mapuse;
88 * Simulation Context type names.
90 private transient List<String> _context;
92 * Knowledge Element type names.
94 private transient List<String> _kname;
98 private transient List<NamedNodeMap> _flows;
100 * Study classifications.
102 private transient List<NamedNodeMap> _sclass;
106 * Database service to check its version, etc.
108 private Database _database;
110 * Injected simulation context type service.
112 private SimulationContextTypeService _simulationContextTypeService;
114 * Injected knowledge element type service.
116 private KnowledgeElementTypeService _knowledgeElementTypeService;
118 * Injected document type service.
120 private DocumentTypeService _documentTypeService;
122 public enum FileNaming {
127 * Validation cycle defined in the XML configuration.
129 public static class ProjectSettingsValidationCycle {
131 * Cycle (document) type name.
133 private transient final String _name;
135 * Array of cycle actors positions in the organization. TODO: Must be replaced by Roles.
137 private transient final Actor[] _actor;
140 * Default constructor.
142 private ProjectSettingsValidationCycle() {
143 this._name = "built-in";
144 this._actor = new Actor[] { null, null, null };
148 * Create a validation cycle definition for the given document type name and actors positions.
151 * the document type name
153 * the array of actors positions
155 private ProjectSettingsValidationCycle(final String name,
156 final Actor[] actor) {
162 * The processed document type name.
164 * @return the document type name
166 public String getName() {
171 * Get an array of cycle actors positions.
173 * @return the array of actors positions
174 * @see org.splat.dal.bo.som.ValidationCycle.Actor
176 public Actor[] getActorTypes() {
181 // ==============================================================================================================================
183 // ==============================================================================================================================
186 * Load workflow configuration from the given file. <br/> Create necessary default staff in the database if it is not initialized yet.
189 * the workflow configuration file
190 * @throws IOException
191 * if there is a file reading or index creation problem
192 * @throws SQLException
193 * if there is a database population problem
195 public void configure(final String filename) throws IOException,
197 if (!_steps.isEmpty()) {
198 return; // Project already configured
201 Database base = getDatabase().getCheckedDB();
202 File config = new File(filename);
203 if (config.exists()) {
204 loadCustomization(config);
206 LOG.fatal("Could not find the database configuration file \""
207 + config.getAbsolutePath() + "\"");
208 throw new FileNotFoundException();
210 base.configure(_reprop);
211 if (!base.isInitialized()) {
213 initialize(); // Populates the database with all necessary stuff
218 * Get ordered list of (transient) study steps.
220 * @return the list of steps from project settings
222 public List<ProjectSettingsService.Step> getAllSteps() {
227 * Return the validation cycles of result documents defined in the workflow, ordered by study activities and ending by the default
228 * validation cycle, if defined.
230 * @return the validation cycles of the workflow
232 public List<ProjectSettingsValidationCycle> getAllValidationCycles() {
237 * Get file naming scheme setting.
239 * @return file naming scheme
240 * @see org.splat.service.technical.ProjectSettingsServiceImpl.FileNaming
242 public FileNaming getFileNamingScheme() {
247 * Get a pattern of study references.
249 * @return the reference pattern
251 public String getReferencePattern() {
256 * Get a pattern of the presentation of version numbers.
258 * @return the version numbers presentation pattern
260 public String getRevisionPattern() {
265 * Get a study step by its sequential number.
271 public ProjectSettingsService.Step getStep(final int number) {
272 ProjectSettingsService.Step res = null;
273 for (int i = 0; i < _steps.size(); i++) {
274 ProjectSettingsService.Step step = _steps.get(i);
275 if (step.getNumber() == number) {
284 * Get steps of the given project element (study or scenario).
287 * the project element (study or scenario)
288 * @return the list of steps
290 public List<ProjectSettingsService.Step> getStepsOf(
291 final Class<? extends ProjectElement> level) {
292 List<ProjectSettingsService.Step> result = new ArrayList<ProjectSettingsService.Step>();
294 for (int i = 0; i < _steps.size(); i++) {
295 ProjectSettingsService.Step step = _steps.get(i);
296 if (step.appliesTo(level)) {
304 * Initialize the database: create all necessary default staff defined in the configuration file.
306 protected void initialize() {
307 createDocumentTypes();
308 createSimulationContextTypes();
309 createKnowledgeElementTypes();
312 // ==============================================================================================================================
313 // Private member function
314 // ==============================================================================================================================
317 * Read the configuration file and fill transient project settings fields.
320 * the configuration XML file
322 private void loadCustomization(final File config) {
324 DocumentBuilderFactory dfactory = javax.xml.parsers.DocumentBuilderFactory
326 DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
328 org.w3c.dom.Document conf = dBuilder.parse(config.getPath());
329 HashMap<String, Node> children = XDOM.getNamedChildNodes(conf
330 .getDocumentElement());
332 // Repository tag initializing the reprop attribute
333 Node child = children.get("database");
334 HashMap<String, Node> datag = XDOM.getNamedChildNodes(child);
336 String disk = datag.get("repository").getAttributes().getNamedItem(
337 "disk").getNodeValue();
338 if (!disk.endsWith("/")) {
341 LOG.info("Database root set to " + disk);
342 _reprop.setProperty("repository", disk);
344 // Formats tag initializing the reference pattern and date attributes
345 child = children.get("formats");
346 datag = XDOM.getNamedChildNodes(child);
348 NamedNodeMap natr = datag.get("references").getAttributes();
349 _pattern = natr.getNamedItem("study").getNodeValue();
351 natr = datag.get("files").getAttributes();
352 _naming = FileNaming.valueOf(natr.getNamedItem("name")
355 natr = datag.get("versions").getAttributes();
356 _versioning = natr.getNamedItem("pattern").getNodeValue();
358 // Activities tag initializing the steps and rex attributes
359 child = children.get("activities");
360 NodeList nlist = child.getChildNodes();
361 List<NamedNodeMap> flist = new ArrayList<NamedNodeMap>();
362 List<String> resultype = new ArrayList<String>();
363 List<NamedNodeMap> clist = new ArrayList<NamedNodeMap>();
365 int snum = 1; // Base number of steps
366 for (int i = 0; i < nlist.getLength(); i++) {
367 child = nlist.item(i);
368 if ("scenario".equals(child.getNodeName())) {
369 NodeList slist = child.getChildNodes();
370 for (int j = 0; j < slist.getLength(); j++) {
371 snum = loadStep(slist.item(j), Scenario.class, snum,
372 flist, clist, resultype);
375 snum = loadStep(child, Study.class, snum, flist, clist,
380 _concycles = loadValidationCycles(children, resultype);
382 if (!getDatabase().getCheckedDB().isInitialized()) {
383 // Load object type definitions
385 child = children.get("documents");
386 nlist = child.getChildNodes();
388 _flows = flist; // Kept for later use in document type definition
389 _sclass = clist; // Kept for later use in simulation context type definition
390 _mapuse = new LinkedHashMap<String, String>();
391 for (int i = 0; i < nlist.getLength(); i++) {
392 child = nlist.item(i);
393 if ("article".equals(child.getNodeName())) {
394 natr = child.getAttributes();
395 String type = natr.getNamedItem("type").getNodeValue();
397 child = natr.getNamedItem("uses");
399 uses = child.getNodeValue();
401 _mapuse.put(type, uses); // Must be added to the map even if no (null) uses
404 // Simulation Contexts tag
405 _context = loadArticles(children, "contexts");
406 // Knowledge Elements tag
407 _kname = loadArticles(children, "knowledges");
409 } catch (Exception error) {
410 LOG.info("Error in customization", error);
415 * Load a step from the given XML node. Return the next step's number.
420 * the class of a step's owner project element - study or scenario
426 * list of classifications
428 * list of flow results
429 * @return the next step's number
431 private int loadStep(final Node node,
432 final Class<? extends ProjectElement> ownerClass, final int snum,
433 final List<NamedNodeMap> flist, final List<NamedNodeMap> clist,
434 final List<String> resultype) {
436 if ("step".equals(node.getNodeName())) {
438 String name = ((Element)node).getAttribute("name");
439 HashMap<String, Node> tags = XDOM.getNamedChildNodes(node);
441 NamedNodeMap natr = tags.get("storage").getAttributes();
442 ProjectSettingsService.Step step = new ProjectSettingsService.Step(
443 snum, ownerClass, natr.getNamedItem("path").getNodeValue());
446 // Keeping flow and classification information for eventual later use
447 natr = tags.get("flow").getAttributes();
449 Node child = natr.getNamedItem("result");
451 resultype.add(child.getNodeValue());
454 child = tags.get("classification");
458 clist.add(child.getAttributes());
461 if (natr.getNamedItem("contents").getNodeValue()
462 .equals("knowledge")) {
463 if (Study.class.equals(ownerClass)) {
465 .error("Error: knowledges must be attached to scenarios.");
467 // TODO In a given scenario, only one step must contain knowledges
468 step._contents.add(KnowledgeElement.class);
471 step._contents.add(Document.class);
474 Element module = (Element) tags.get("module");
475 if (module != null) {
476 step.setModule(module.getAttribute("name"));
486 * Get custom validation cycles.
491 * list of result types
492 * @return return list of validation cycles
494 private List<ProjectSettingsValidationCycle> loadValidationCycles(
495 final Map<String, Node> children, final List<String> resultype) {
496 Node child = children.get("validations");
497 List<ProjectSettingsValidationCycle> cycles = new ArrayList<ProjectSettingsValidationCycle>();
498 Map<String, Node> datag = XDOM.getNamedChildNodes(child);
501 String[] step = { "review", "approval", "acceptance" };
502 resultype.add("default");
503 for (Iterator<String> i = resultype.iterator(); i.hasNext();) {
504 Actor[] actor = { null, null, null };
505 String name = i.next();
506 child = datag.get(name);
508 // Document type is the subject of a validation
509 natr = child.getAttributes();
510 for (int j = 0; j < step.length; j++) {
511 child = natr.getNamedItem(step[j]);
513 actor[j] = Actor.valueOf(child.getNodeValue()); // Validation step is required
516 cycles.add(new ProjectSettingsValidationCycle(name, actor));
519 cycles.add(new ProjectSettingsValidationCycle()); // Adds the built-in validation cycle
524 * Read list of articles types.
527 * XML nodes containing articles
529 * the name of the list of articles
530 * @return list of articles types
532 private List<String> loadArticles(final Map<String, Node> children,
533 final String listName) {
534 Node child = children.get(listName);
535 NodeList nlist = child.getChildNodes();
537 List<String> articles = new ArrayList<String>();
538 for (int i = 0; i < nlist.getLength(); i++) {
539 child = nlist.item(i);
540 if (child.getNodeName().equals("article")) {
541 articles.add(child.getAttributes().getNamedItem("type")
549 * Create in the database document types defined in the custom configuration.
551 private void createDocumentTypes() {
552 DocumentType.Properties tprop = new DocumentType.Properties();
553 Map<String, List<ProjectSettingsService.Step>> mapsteps = new HashMap<String, List<ProjectSettingsService.Step>>();
554 Map<String, ProjectSettingsService.Step> mapresult = new HashMap<String, ProjectSettingsService.Step>();
555 Map<String, DocumentType> maptype = new HashMap<String, DocumentType>();
557 List<ProjectSettingsService.Step> slist = null; // List of Steps to which each document type is valid
558 int snum = 0; // Step number
561 for (Iterator<NamedNodeMap> i = _flows.iterator(); i.hasNext(); snum++) {
562 NamedNodeMap flow = i.next();
563 ProjectSettingsService.Step step = _steps.get(snum);
564 String[] contents = flow.getNamedItem("contents").getNodeValue()
566 for (int j = 0; j < contents.length; j++) {
568 if (!_mapuse.containsKey(type)) {
569 LOG.warn("Undefined \"" + type + "\" document type.");
572 slist = mapsteps.get(type);
574 slist = new ArrayList<ProjectSettingsService.Step>();
577 mapsteps.put(type, slist);
579 Node result = flow.getNamedItem("result");
580 if (result != null) {
581 mapresult.put(result.getNodeValue(), step);
585 DocumentType tdoc = null;
586 Set<String> tset = _mapuse.keySet();
587 ProjectSettingsService.Step step;
588 for (Iterator<String> i = tset.iterator(); i.hasNext();) {
590 slist = mapsteps.get(type);
591 uses = _mapuse.get(type);
592 step = mapresult.get(type);
595 tprop.setName(type).setStep(
596 slist.toArray(new ProjectSettingsService.Step[slist
599 tdoc = maptype.get(uses);
601 LOG.warn("Undefined \"" + uses + "\" document type.");
607 tprop.setResult(step);
610 tprop.disableCheck();
611 tdoc = getDocumentTypeService().createType(tprop); // Creation of Document Types
612 getDocumentTypeService().approve(tdoc);
613 maptype.put(type, tdoc);
615 } catch (Exception error) {
616 LOG.warn("Error creating document types, reason:", error); // Should not happen
621 * Create in the database knowledge types defined in the custom configuration.
623 private void createKnowledgeElementTypes() {
625 KnowledgeElementType ktype = getKnowledgeElementTypeService()
626 .createType("usecase"); // Internal reserved knowledge element type
627 getKnowledgeElementTypeService().reserve(ktype);
628 for (Iterator<String> i = _kname.iterator(); i.hasNext();) {
629 String type = i.next();
631 ktype = getKnowledgeElementTypeService().createType(type); // Knowledge Elements Types defined in the configuration
632 getKnowledgeElementTypeService().approve(ktype);
634 } catch (Exception error) {
635 LOG.warn("Error creating knowledge types, reason:", error); // Should not happen
640 * Create in the database simulation contexts types defined in the custom configuration.
642 private void createSimulationContextTypes() {
643 Map<String, ProjectSettingsService.Step> mapstep = new HashMap<String, ProjectSettingsService.Step>();
645 for (Iterator<NamedNodeMap> i = _sclass.iterator(); i.hasNext(); snum++) {
646 NamedNodeMap clatr = i.next();
648 String[] clist = clatr.getNamedItem("context").getNodeValue()
650 for (int j = 0; j < clist.length; j++) {
651 mapstep.put(clist[j], _steps.get(snum));
656 SimulationContextType tctex = null;
657 for (Iterator<String> i = _context.iterator(); i.hasNext();) {
658 String type = i.next();
659 if (mapstep.containsKey(type)) {
660 tctex = getSimulationContextTypeService().createType(type,
661 mapstep.get(type)); // Creation of Simulation Context Types
662 getSimulationContextTypeService().approve(tctex);
665 .warn("Could not find \""
667 + "\" classification. Simulation Context type ignored.");
670 } catch (Exception error) {
671 LOG.warn("Error creating context types, reason:", error); // Should not happen
678 * @return the database
680 public Database getDatabase() {
688 * the database to set
690 public void setDatabase(final Database database) {
691 _database = database;
695 * Get the simulationContextTypeService.
697 * @return the simulationContextTypeService
699 public SimulationContextTypeService getSimulationContextTypeService() {
700 return _simulationContextTypeService;
704 * Set the simulationContextTypeService.
706 * @param simulationContextTypeService
707 * the simulationContextTypeService to set
709 public void setSimulationContextTypeService(
710 final SimulationContextTypeService simulationContextTypeService) {
711 _simulationContextTypeService = simulationContextTypeService;
715 * Get the knowledgeElementTypeService.
717 * @return the knowledgeElementTypeService
719 public KnowledgeElementTypeService getKnowledgeElementTypeService() {
720 return _knowledgeElementTypeService;
724 * Set the knowledgeElementTypeService.
726 * @param knowledgeElementTypeService
727 * the knowledgeElementTypeService to set
729 public void setKnowledgeElementTypeService(
730 final KnowledgeElementTypeService knowledgeElementTypeService) {
731 _knowledgeElementTypeService = knowledgeElementTypeService;
735 * Get the documentTypeService.
737 * @return the documentTypeService
739 public DocumentTypeService getDocumentTypeService() {
740 return _documentTypeService;
744 * Set the documentTypeService.
746 * @param documentTypeService
747 * the documentTypeService to set
749 public void setDocumentTypeService(
750 final DocumentTypeService documentTypeService) {
751 _documentTypeService = documentTypeService;