1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 package org.osjava.sj.loader.util;
34
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.util.Properties;
38
39 import javax.xml.parsers.DocumentBuilder;
40 import javax.xml.parsers.DocumentBuilderFactory;
41 import javax.xml.parsers.ParserConfigurationException;
42
43 import org.w3c.dom.Document;
44 import org.w3c.dom.Element;
45 import org.w3c.dom.NamedNodeMap;
46 import org.w3c.dom.Node;
47 import org.w3c.dom.NodeList;
48 import org.xml.sax.SAXException;
49
50 /***
51 * Loads properties using the DOM API from an InputStream containing XML
52 */
53 public class XmlProperties extends AbstractProperties {
54
55 public XmlProperties() {
56 super();
57 }
58
59 public XmlProperties(Properties props) {
60 super(props);
61 }
62
63 public void load(InputStream in) throws IOException {
64 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
65 DocumentBuilder builder = null;
66 Document document = null;
67
68 try {
69 builder = factory.newDocumentBuilder();
70 document = builder.parse(in);
71 } catch (ParserConfigurationException pce) {
72 throw new IOException("Unable to get DocumentBuilder from factory. " + pce.getMessage());
73 }
74 catch (SAXException se) {
75 throw new IOException("Unable to parse document. " + se.getMessage());
76 }
77
78 if (document != null) {
79 loadDocument(document);
80 }
81 }
82
83 private void loadDocument(Document document) {
84 Element root = document.getDocumentElement();
85 String level = root.getNodeName();
86 processChildren(level, root);
87 }
88
89 private void processChildren(String level, Node node) {
90 NodeList children = node.getChildNodes();
91 for(int i=0;i<children.getLength();i++) {
92 Node child = children.item(i);
93 addNode(level, child);
94 if (child.hasAttributes()) {
95 String attributeLevel = level + getDelimiter() + child.getNodeName();
96 addAttributes(attributeLevel, child.getAttributes());
97 }
98 }
99 }
100
101 private void addNode(String level, Node node) {
102 switch (node.getNodeType()) {
103 case Node.ELEMENT_NODE :
104 level = level + getDelimiter() + node.getNodeName();
105 break;
106 case Node.TEXT_NODE :
107 store(level, node.getNodeValue());
108 break;
109 }
110
111 processChildren(level, node);
112 }
113
114 private void addAttributes(String level, NamedNodeMap map) {
115 for(int i=0;i<map.getLength();i++) {
116 Node attribute = map.item(i);
117 String attributeLevel = level + getDelimiter() + attribute.getNodeName();
118 store(attributeLevel, attribute.getNodeValue());
119 }
120 }
121
122 private void store(String name, String value) {
123 if (value.trim().length() > 0) {
124 setProperty(name, value);
125 }
126 }
127 }