]> SALOME platform Git repositories - tools/siman.git/blob - Workspace/Siman-Common/src/org/splat/service/technical/ProjectSettingsServiceImpl.java
Salome HOME
Refactoring continues: UserService is created instead of UserDirectory. Database...
[tools/siman.git] / Workspace / Siman-Common / src / org / splat / service / technical / ProjectSettingsServiceImpl.java
1 package org.splat.service.technical;
2
3 /**
4  * 
5  * @author    Daniel Brunier-Coulin
6  * @copyright OPEN CASCADE 2012
7  */
8
9 import java.io.File;
10 import java.io.FileNotFoundException;
11 import java.io.IOException;
12 import java.sql.SQLException;
13 import java.util.HashMap;
14 import java.util.Iterator;
15 import java.util.LinkedHashMap;
16 import java.util.List;
17 import java.util.Properties;
18 import java.util.Set;
19 import java.util.Vector;
20
21 import javax.xml.parsers.DocumentBuilder;
22 import javax.xml.parsers.DocumentBuilderFactory;
23
24 import org.apache.log4j.Logger;
25 import org.w3c.dom.NamedNodeMap;
26 import org.w3c.dom.Node;
27 import org.w3c.dom.NodeList;
28
29 import org.splat.dal.bo.som.Document;
30 import org.splat.dal.bo.som.DocumentType;
31 import org.splat.dal.bo.som.KnowledgeElement;
32 import org.splat.dal.bo.som.KnowledgeElementType;
33 import org.splat.dal.bo.som.ProjectElement;
34 import org.splat.dal.bo.som.Scenario;
35 import org.splat.dal.bo.som.SimulationContextType;
36 import org.splat.dal.bo.som.Study;
37 import org.splat.dal.bo.som.ValidationCycle.Actor;
38 import org.splat.dal.dao.som.Database;
39 import org.splat.manox.XDOM;
40 import org.splat.service.DocumentTypeService;
41 import org.splat.service.KnowledgeElementTypeService;
42 import org.splat.service.SimulationContextService;
43
44 public class ProjectSettingsServiceImpl implements ProjectSettingsService {
45
46         /**
47          * The logger for the service.
48          */
49         protected final static Logger logger = Logger
50                         .getLogger(ProjectSettingsServiceImpl.class);
51
52         // Non persistent configuration information
53         private Properties reprop; // Repository settings
54         private String pattern; // Pattern of study references
55         private FileNaming naming; // Scheme of file names stored into the repository
56         private String versioning; // Pattern of the presentation of version numbers
57         private Vector<ProjectSettingsService.Step> steps; // Ordered list of (transient) study steps
58         private Vector<ProjectSettingsValidationCycle> concycles; // Configuration document validation cycles
59
60         // Temporary attributes initialized from the configuration file for populating the database with object types
61         private LinkedHashMap<String, String> mapuse; // Document type names and uses mapping
62         private Vector<String> context; // Simulation Context type names
63         private Vector<String> kname; // Knowledge Element type names
64         private Vector<NamedNodeMap> flows; // Document flows
65         private Vector<NamedNodeMap> sclass; // Study classifications
66
67         // Other resources
68         private static ProjectSettingsServiceImpl my = null; // Singleton instance
69         private Database _database;
70         /**
71          * Injected simulation context service.
72          */
73         private SimulationContextService _simulationContextService;
74         /**
75          * Injected knowledge element type service.
76          */
77         private KnowledgeElementTypeService _knowledgeElementTypeService;
78         /**
79          * Injected document type service.
80          */
81         private DocumentTypeService _documentTypeService;
82
83         public enum FileNaming {
84                 title, encoded, asis
85         }
86
87         public static class ProjectSettingsValidationCycle {
88                 // -----------------------------------
89                 private String name;
90                 private Actor[] actor;
91
92                 private ProjectSettingsValidationCycle() {
93                         this.name = "built-in";
94                         this.actor = new Actor[] { null, null, null };
95                 }
96
97                 private ProjectSettingsValidationCycle(String name, Actor[] actor) {
98                         this.name = name;
99                         this.actor = actor;
100                 }
101
102                 public String getName() {
103                         return name;
104                 }
105
106                 public Actor[] getActorTypes() {
107                         return actor;
108                 }
109         }
110
111         // ==============================================================================================================================
112         // Construction
113         // ==============================================================================================================================
114         protected ProjectSettingsServiceImpl() {
115                 // ----------------------------
116                 reprop = new Properties();
117                 steps = new Vector<ProjectSettingsService.Step>();
118                 my = this;
119         }
120
121         // ==============================================================================================================================
122         // Public functions
123         // ==============================================================================================================================
124
125         public void configure(String filename) throws IOException, SQLException {
126                 // ---------------------------------------
127                 if (!steps.isEmpty())
128                         return; // Project already configured
129
130                 Database base = getDatabase().getCheckedDB();
131                 File config = new File(filename);
132                 if (config.exists()) {
133                         loadCustomization(config);
134                 } else {
135                         logger.fatal("Could not find the database configuration file \""
136                                         + config.getAbsolutePath() + "\"");
137                         throw new FileNotFoundException();
138                 }
139                 base.configure(reprop);
140                 if (!base.isInitialized()) {
141                         base.initialize();
142                         initialize(); // Populates the database with all necessary stuff
143                 }
144         }
145
146         public List<ProjectSettingsService.Step> getAllSteps() {
147                 // ---------------------------------------
148                 return steps;
149         }
150
151         /**
152          * Return the validation cycles of result documents defined in the workflow, ordered by study activities and ending by the default
153          * validation cycle, if defined.
154          * 
155          * @return the validation cycles of the workflow
156          */
157         public static List<ProjectSettingsValidationCycle> getAllValidationCycles() {
158                 // -------------------------------------------------------------
159                 return my.concycles;
160         }
161
162         public FileNaming getFileNamingScheme() {
163                 // -----------------------------------------------
164                 return naming;
165         }
166
167         public static ProjectSettingsValidationCycle getNewValidationCycle() {
168                 // ------------------------------------------------------
169                 return new ProjectSettingsValidationCycle();
170         }
171
172         public String getReferencePattern() {
173                 return pattern;
174         }
175
176         public String getRevisionPattern() {
177                 // ------------------------------------------
178                 return versioning;
179         }
180
181         public static ProjectSettingsService.Step getStep(int number) {
182                 // ---------------------------------------
183                 for (int i = 0; i < my.steps.size(); i++) {
184                         ProjectSettingsService.Step step = my.steps.get(i);
185                         if (step.number == number)
186                                 return step;
187                 }
188                 return null;
189         }
190
191         public List<ProjectSettingsService.Step> getStepsOf(
192                         Class<? extends ProjectElement> level) {
193                 // ---------------------------------------------------------------------------
194                 Vector<ProjectSettingsService.Step> result = new Vector<ProjectSettingsService.Step>();
195
196                 for (int i = 0; i < steps.size(); i++) {
197                         ProjectSettingsService.Step step = steps.get(i);
198                         if (step.appliesTo(level))
199                                 result.add(step);
200                 }
201                 return result;
202         }
203
204         // ==============================================================================================================================
205         // Protected member function
206         // ==============================================================================================================================
207
208         public void initialize() {
209                 // ----------------------------
210                 createDocumentTypes();
211                 createSimulationContextTypes();
212                 createKnowledgeElementTypes();
213         }
214
215         // ==============================================================================================================================
216         // Private member function
217         // ==============================================================================================================================
218
219         private void loadCustomization(File config) {
220                 // --------------------------------------------
221                 try {
222                         DocumentBuilderFactory dfactory = javax.xml.parsers.DocumentBuilderFactory
223                                         .newInstance();
224                         DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
225
226                         org.w3c.dom.Document conf = dBuilder.parse(config.getPath());
227                         HashMap<String, Node> children = XDOM.getNamedChildNodes(conf
228                                         .getDocumentElement());
229
230                         // Repository tag initializing the reprop attribute
231                         Node child = children.get("database");
232                         HashMap<String, Node> datag = XDOM.getNamedChildNodes(child);
233
234                         String disk = datag.get("repository").getAttributes().getNamedItem(
235                                         "disk").getNodeValue();
236                         if (!disk.endsWith("/"))
237                                 disk = disk + "/";
238                         logger.info("Database root set to " + disk);
239                         reprop.setProperty("repository", disk);
240
241                         // Formats tag initializing the reference pattern and date attributes
242                         child = children.get("formats");
243                         datag = XDOM.getNamedChildNodes(child);
244
245                         NamedNodeMap natr = datag.get("references").getAttributes();
246                         pattern = natr.getNamedItem("study").getNodeValue();
247
248                         natr = datag.get("files").getAttributes();
249                         naming = FileNaming.valueOf(natr.getNamedItem("name")
250                                         .getNodeValue());
251
252                         natr = datag.get("versions").getAttributes();
253                         versioning = natr.getNamedItem("pattern").getNodeValue();
254
255                         // Activities tag initializing the steps and rex attributes
256                         child = children.get("activities");
257                         NodeList nlist = child.getChildNodes();
258                         Vector<NamedNodeMap> flist = new Vector<NamedNodeMap>();
259                         Vector<String> resultype = new Vector<String>();
260                         Vector<NamedNodeMap> clist = new Vector<NamedNodeMap>();
261
262                         int snum = 1; // Base number of steps
263                         for (int i = 0; i < nlist.getLength(); i++) {
264                                 child = nlist.item(i);
265                                 if (child.getNodeName().equals("scenario")) {
266                                         NodeList slist = child.getChildNodes();
267                                         for (int j = 0; j < slist.getLength(); j++) {
268                                                 child = slist.item(j);
269                                                 if (!child.getNodeName().equals("step"))
270                                                         continue;
271                                                 HashMap<String, Node> tags = XDOM
272                                                                 .getNamedChildNodes(child);
273
274                                                 natr = tags.get("storage").getAttributes();
275                                                 ProjectSettingsService.Step step = new ProjectSettingsService.Step(
276                                                                 snum, Scenario.class, natr.getNamedItem("path")
277                                                                                 .getNodeValue());
278
279                                                 // Keeping flow and classification information for eventual later use
280                                                 natr = tags.get("flow").getAttributes();
281                                                 flist.add(natr);
282                                                 child = natr.getNamedItem("result");
283                                                 if (child != null)
284                                                         resultype.add(child.getNodeValue());
285
286                                                 child = tags.get("classification");
287                                                 if (child != null)
288                                                         clist.add(child.getAttributes());
289                                                 else
290                                                         clist.add(null);
291
292                                                 if (natr.getNamedItem("contents").getNodeValue()
293                                                                 .equals("knowledge")) {
294                                                         // TODO In a given scenario, only one step must contain knowledges
295                                                         step.contents.add(KnowledgeElement.class);
296                                                 } else {
297                                                         step.contents.add(Document.class);
298                                                 }
299                                                 steps.add(step);
300                                                 snum += 1;
301                                         }
302                                 } else {
303                                         if (!child.getNodeName().equals("step"))
304                                                 continue;
305                                         HashMap<String, Node> tags = XDOM.getNamedChildNodes(child);
306
307                                         natr = tags.get("storage").getAttributes(); // Mandatory information
308                                         ProjectSettingsService.Step step = new ProjectSettingsService.Step(
309                                                         snum, Study.class, natr.getNamedItem("path")
310                                                                         .getNodeValue());
311
312                                         // Keeping flow and classification information for eventual later use
313                                         natr = tags.get("flow").getAttributes();
314                                         flist.add(natr);
315                                         child = natr.getNamedItem("result");
316                                         if (child != null)
317                                                 resultype.add(child.getNodeValue());
318
319                                         child = tags.get("classification"); // Optional information
320                                         if (child != null)
321                                                 clist.add(child.getAttributes());
322                                         else
323                                                 clist.add(null);
324
325                                         if (natr.getNamedItem("contents").getNodeValue().equals(
326                                                         "knowledge")) {
327                                                 // TODO Error: knowledges must be attached to scenarios
328                                         } else {
329                                                 step.contents.add(Document.class);
330                                         }
331                                         steps.add(step);
332                                         snum += 1;
333                                 }
334                         }
335                         // Validations tag
336                         child = children.get("validations");
337                         concycles = new Vector<ProjectSettingsValidationCycle>();
338                         datag = XDOM.getNamedChildNodes(child);
339
340                         String[] step = { "review", "approval", "acceptance" };
341                         resultype.add("default");
342                         for (Iterator<String> i = resultype.iterator(); i.hasNext();) {
343                                 Actor[] actor = { null, null, null };
344                                 String name = i.next();
345                                 child = datag.get(name);
346                                 if (child == null)
347                                         continue; // Document type not subject of any validation
348                                 natr = child.getAttributes();
349                                 for (int j = 0; j < step.length; j++) {
350                                         child = natr.getNamedItem(step[j]);
351                                         if (child == null)
352                                                 continue; // Validation step not required
353                                         actor[j] = Actor.valueOf(child.getNodeValue());
354                                 }
355                                 concycles.add(new ProjectSettingsValidationCycle(name, actor));
356                         }
357                         concycles.add(new ProjectSettingsValidationCycle()); // Adds the built-in validation cycle
358
359                         if (getDatabase().getCheckedDB().isInitialized())
360                                 return; // No need to load object type definitions as they are already stored
361
362                         // Documents tag
363                         child = children.get("documents");
364                         nlist = child.getChildNodes();
365
366                         flows = flist; // Kept for later use in document type definition
367                         sclass = clist; // Kept for later use in simulation context type definition
368                         mapuse = new LinkedHashMap<String, String>();
369                         for (int i = 0; i < nlist.getLength(); i++) {
370                                 child = nlist.item(i);
371                                 if (!child.getNodeName().equals("article"))
372                                         continue;
373
374                                 natr = child.getAttributes();
375                                 String type = natr.getNamedItem("type").getNodeValue();
376                                 String uses = null;
377                                 child = natr.getNamedItem("uses");
378                                 if (child != null)
379                                         uses = child.getNodeValue();
380                                 mapuse.put(type, uses); // Must be added to the map even if no (null) uses
381                         }
382                         // Simulation Contexts tag
383                         child = children.get("contexts");
384                         nlist = child.getChildNodes();
385
386                         context = new Vector<String>();
387                         for (int i = 0; i < nlist.getLength(); i++) {
388                                 child = nlist.item(i);
389                                 if (!child.getNodeName().equals("article"))
390                                         continue;
391
392                                 context.add(child.getAttributes().getNamedItem("type")
393                                                 .getNodeValue());
394                         }
395                         // Knowledge Elements tag
396                         child = children.get("knowledges");
397                         nlist = child.getChildNodes();
398
399                         kname = new Vector<String>();
400                         for (int i = 0; i < nlist.getLength(); i++) {
401                                 child = nlist.item(i);
402                                 if (!child.getNodeName().equals("article"))
403                                         continue;
404
405                                 kname.add(child.getAttributes().getNamedItem("type")
406                                                 .getNodeValue());
407                         }
408                 } catch (Exception error) {
409                         logger.info("Error in customization", error);
410                 }
411         }
412
413         private void createDocumentTypes() {
414                 // -----------------------------------
415                 DocumentType.Properties tprop = new DocumentType.Properties();
416                 HashMap<String, Vector<ProjectSettingsService.Step>> mapsteps = new HashMap<String, Vector<ProjectSettingsService.Step>>();
417                 HashMap<String, ProjectSettingsService.Step> mapresult = new HashMap<String, ProjectSettingsService.Step>();
418                 HashMap<String, DocumentType> maptype = new HashMap<String, DocumentType>();
419
420                 Vector<ProjectSettingsService.Step> slist = null; // List of Steps to which each document type is valid
421                 int snum = 0; // Step number
422                 String type = null;
423                 String uses = null;
424                 for (Iterator<NamedNodeMap> i = flows.iterator(); i.hasNext(); snum++) {
425                         NamedNodeMap flow = i.next();
426                         ProjectSettingsService.Step step = steps.get(snum);
427                         String[] contents = flow.getNamedItem("contents").getNodeValue()
428                                         .split(",");
429                         for (int j = 0; j < contents.length; j++) {
430                                 type = contents[j];
431                                 if (!mapuse.containsKey(type)) {
432                                         logger.warn("Undefined \"" + type + "\" document type.");
433                                         continue;
434                                 }
435                                 slist = mapsteps.get(type);
436                                 if (slist == null)
437                                         slist = new Vector<ProjectSettingsService.Step>();
438                                 slist.add(step);
439                                 mapsteps.put(type, slist);
440                         }
441                         Node result = flow.getNamedItem("result");
442                         if (result != null)
443                                 mapresult.put(result.getNodeValue(), step);
444                 }
445                 try {
446                         DocumentType tdoc = null;
447                         Set<String> tset = mapuse.keySet();
448                         ProjectSettingsService.Step step;
449                         for (Iterator<String> i = tset.iterator(); i.hasNext();) {
450                                 type = i.next();
451                                 slist = mapsteps.get(type);
452                                 uses = mapuse.get(type);
453                                 step = mapresult.get(type);
454
455                                 tprop.clear();
456                                 tprop.setName(type).setStep(
457                                                 slist.toArray(new ProjectSettingsService.Step[slist
458                                                                 .size()]));
459                                 if (uses != null) {
460                                         tdoc = maptype.get(uses);
461                                         if (tdoc == null)
462                                                 logger
463                                                                 .warn("Undefined \"" + uses
464                                                                                 + "\" document type.");
465                                         else
466                                                 tprop.setUses(tdoc);
467                                 }
468                                 if (step != null)
469                                         tprop.setResult(step);
470
471                                 tprop.disableCheck();
472                                 tdoc = getDocumentTypeService().createType(tprop); // Creation of Document Types
473                                 getDocumentTypeService().approve(tdoc);
474                                 maptype.put(type, tdoc);
475                         }
476                 } catch (Exception error) {
477                         logger.warn("Error creating document types, reason:", error); // Should not happen
478                 }
479         }
480
481         private void createKnowledgeElementTypes() {
482                 // -------------------------------------------
483                 try {
484                         KnowledgeElementType ktype = getKnowledgeElementTypeService()
485                                         .createType("usecase"); // Internal reserved knowledge element type
486                         getKnowledgeElementTypeService().reserve(ktype);
487                         for (Iterator<String> i = kname.iterator(); i.hasNext();) {
488                                 String type = i.next();
489
490                                 ktype = getKnowledgeElementTypeService().createType(type); // Knowledge Elements Types defined in the configuration
491                                 getKnowledgeElementTypeService().approve(ktype);
492                         }
493                 } catch (Exception error) {
494                         logger.warn("Error creating knowledge types, reason:", error); // Should not happen
495                 }
496         }
497
498         private void createSimulationContextTypes() {
499                 // --------------------------------------------
500                 HashMap<String, ProjectSettingsService.Step> mapstep = new HashMap<String, ProjectSettingsService.Step>();
501                 int snum = 0;
502                 for (Iterator<NamedNodeMap> i = sclass.iterator(); i.hasNext(); snum++) {
503                         NamedNodeMap clatr = i.next();
504                         if (clatr == null)
505                                 continue;
506
507                         String[] clist = clatr.getNamedItem("context").getNodeValue()
508                                         .split(",");
509                         for (int j = 0; j < clist.length; j++) {
510                                 mapstep.put(clist[j], steps.get(snum));
511                         }
512                 }
513                 try {
514                         SimulationContextType tctex = null;
515                         for (Iterator<String> i = context.iterator(); i.hasNext();) {
516                                 String type = i.next();
517                                 if (!mapstep.containsKey(type)) {
518                                         logger
519                                                         .warn("Could not find \""
520                                                                         + type
521                                                                         + "\" classification. Simulation Context type ignored.");
522                                         continue;
523                                 }
524                                 tctex = getSimulationContextService().createType(type,
525                                                 mapstep.get(type)); // Creation of Simulation Context Types
526                                 getSimulationContextService().approve(tctex);
527                         }
528                 } catch (Exception error) {
529                         logger.warn("Error creating context types, reason:", error); // Should not happen
530                 }
531         }
532
533         /**
534          * Get the database.
535          * 
536          * @return the database
537          */
538         public Database getDatabase() {
539                 return _database;
540         }
541
542         /**
543          * Set the database.
544          * 
545          * @param database
546          *            the database to set
547          */
548         public void setDatabase(Database database) {
549                 _database = database;
550         }
551
552         /**
553          * Get the simulationContextService.
554          * 
555          * @return the simulationContextService
556          */
557         public SimulationContextService getSimulationContextService() {
558                 return _simulationContextService;
559         }
560
561         /**
562          * Set the simulationContextService.
563          * 
564          * @param simulationContextService
565          *            the simulationContextService to set
566          */
567         public void setSimulationContextService(
568                         SimulationContextService simulationContextService) {
569                 _simulationContextService = simulationContextService;
570         }
571
572         /**
573          * Get the knowledgeElementTypeService.
574          * 
575          * @return the knowledgeElementTypeService
576          */
577         public KnowledgeElementTypeService getKnowledgeElementTypeService() {
578                 return _knowledgeElementTypeService;
579         }
580
581         /**
582          * Set the knowledgeElementTypeService.
583          * 
584          * @param knowledgeElementTypeService
585          *            the knowledgeElementTypeService to set
586          */
587         public void setKnowledgeElementTypeService(
588                         KnowledgeElementTypeService knowledgeElementTypeService) {
589                 _knowledgeElementTypeService = knowledgeElementTypeService;
590         }
591
592         /**
593          * Get the documentTypeService.
594          * @return the documentTypeService
595          */
596         public DocumentTypeService getDocumentTypeService() {
597                 return _documentTypeService;
598         }
599
600         /**
601          * Set the documentTypeService.
602          * @param documentTypeService the documentTypeService to set
603          */
604         public void setDocumentTypeService(DocumentTypeService documentTypeService) {
605                 _documentTypeService = documentTypeService;
606         }
607 }