KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > cache > xml > XmlHelper


1 /*
2  * JBoss, Home of Professional Open Source
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7 package org.jboss.cache.xml;
8
9 import org.apache.commons.logging.Log;
10 import org.apache.commons.logging.LogFactory;
11 import org.w3c.dom.Document JavaDoc;
12 import org.w3c.dom.Element JavaDoc;
13 import org.w3c.dom.Node JavaDoc;
14 import org.w3c.dom.NodeList JavaDoc;
15 import org.w3c.dom.Text JavaDoc;
16 import org.xml.sax.InputSource JavaDoc;
17 import org.xml.sax.SAXException JavaDoc;
18 import org.xml.sax.SAXParseException JavaDoc;
19
20 import javax.xml.parsers.DocumentBuilder JavaDoc;
21 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
22 import java.io.ByteArrayInputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.util.Properties JavaDoc;
26
27 /**
28  * A simple XML utility class for reading configuration elements
29  *
30  * @author <a HREF="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a>
31  */

32 public class XmlHelper
33 {
34    private static Log log = LogFactory.getLog(XmlHelper.class);
35    public static final String JavaDoc ROOT = "mbean";
36    public static final String JavaDoc ATTR = "attribute";
37    public static final String JavaDoc CONFIG_ATTR = "config";
38    public static final String JavaDoc NAME = "name";
39
40
41    /**
42     * Returns the contents of a specific node of given tagName, provided a certain attribute exists and contains value myValue.
43     *
44     * @param elem
45     * @param myName
46     * @param tagName
47     * @param attributeName
48     */

49    public static String JavaDoc getTagContents(Element JavaDoc elem, String JavaDoc myName, String JavaDoc tagName, String JavaDoc attributeName)
50    {
51       NodeList JavaDoc list = elem.getElementsByTagName(tagName);
52
53       for (int s = 0; s < list.getLength(); s++)
54       {
55          org.w3c.dom.Node JavaDoc node = list.item(s);
56          if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE)
57             continue;
58
59          Element JavaDoc element = (Element JavaDoc) node;
60          String JavaDoc name = element.getAttribute(attributeName);
61          if (name.equals(myName))
62          {
63             return getElementContent(element, true);
64          }
65       }
66       return null;
67    }
68
69    /**
70     * Retrieves the value of a given attribute for the first encountered instance of a tag in an element.
71     *
72     * @param elem
73     * @param tagName
74     * @param attributeName
75     */

76    public static String JavaDoc getAttributeValue(Element JavaDoc elem, String JavaDoc tagName, String JavaDoc attributeName)
77    {
78       NodeList JavaDoc list = elem.getElementsByTagName(tagName);
79
80       for (int s = 0; s < list.getLength(); s++)
81       {
82          org.w3c.dom.Node JavaDoc node = list.item(s);
83          if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE)
84             continue;
85
86          Element JavaDoc element = (Element JavaDoc) node;
87          return element.getAttribute(attributeName);
88
89       }
90       return null;
91    }
92
93    public static Element JavaDoc getConfigSubElement(Element JavaDoc element)
94    {
95       return getSubElement(element, CONFIG_ATTR);
96    }
97
98    public static Element JavaDoc getSubElement(Element JavaDoc element, String JavaDoc subElementName)
99    {
100       NodeList JavaDoc nl = element.getChildNodes();
101       for (int i = 0; i < nl.getLength(); i++)
102       {
103          Node JavaDoc node = nl.item(i);
104          if (node.getNodeType() == Node.ELEMENT_NODE && subElementName.equals(((Element JavaDoc) node).getTagName()))
105          {
106             return (Element JavaDoc) node;
107          }
108       }
109
110       if (log.isDebugEnabled()) log.debug("getSubElement(): Does not exist for " + subElementName);
111       return null;
112    }
113
114    public static String JavaDoc getElementContent(Element JavaDoc element, boolean trim)
115    {
116       NodeList JavaDoc nl = element.getChildNodes();
117       String JavaDoc attributeText = "";
118       for (int i = 0; i < nl.getLength(); i++)
119       {
120          Node JavaDoc n = nl.item(i);
121          if (n instanceof Text JavaDoc)
122          {
123             attributeText += ((Text JavaDoc) n).getData();
124          }
125       } // end of for ()
126
if (trim)
127          attributeText = attributeText.trim();
128       return attributeText;
129    }
130
131    public static String JavaDoc readStringContents(Element JavaDoc element, String JavaDoc tagName)
132    {
133       NodeList JavaDoc nodes = element.getElementsByTagName(tagName);
134       if (nodes.getLength() > 0)
135       {
136          Node JavaDoc node = nodes.item(0);
137          Element JavaDoc ne = (Element JavaDoc) node;
138          NodeList JavaDoc nl2 = ne.getChildNodes();
139          Node JavaDoc node2 = nl2.item(0);
140          if (node2 != null)
141          {
142             String JavaDoc value = node2.getNodeValue();
143             if (value == null)
144                return "";
145             return value.trim();
146          }
147          else
148          {
149             return "";
150          }
151       }
152       else
153       {
154          return "";
155       }
156    }
157
158    public static String JavaDoc escapeBackslashes(String JavaDoc value)
159    {
160       StringBuffer JavaDoc buf = new StringBuffer JavaDoc(value);
161       for (int looper = 0; looper < buf.length(); looper++)
162       {
163          char curr = buf.charAt(looper);
164          char next = 0;
165          if (looper + 1 < buf.length())
166             next = buf.charAt(looper + 1);
167
168          if (curr == '\\')
169          {
170             if (next != '\\')
171             { // only if not already escaped
172
buf.insert(looper, '\\'); // escape backslash
173
}
174             looper++; // skip past extra backslash (either the one we added or existing)
175
}
176       }
177       return buf.toString();
178    }
179
180    public static Properties JavaDoc readPropertiesContents(Element JavaDoc element, String JavaDoc tagName) throws IOException JavaDoc
181    {
182       String JavaDoc stringContents = readStringContents(element, tagName);
183       if (stringContents == null) return new Properties JavaDoc();
184       // JBCACHE-531: escape all backslash characters
185
stringContents = escapeBackslashes(stringContents);
186       ByteArrayInputStream JavaDoc is = new ByteArrayInputStream JavaDoc(stringContents.trim().getBytes("ISO8859_1"));
187       Properties JavaDoc properties = new Properties JavaDoc();
188       properties.load(is);
189       is.close();
190       return properties;
191    }
192
193    public static boolean readBooleanContents(Element JavaDoc element, String JavaDoc tagName)
194    {
195       return readBooleanContents(element, tagName, false);
196    }
197
198    public static boolean readBooleanContents(Element JavaDoc element, String JavaDoc tagName, boolean defaultValue)
199    {
200       String JavaDoc val = readStringContents(element, tagName);
201       if (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false"))
202       {
203          return Boolean.valueOf(val);
204       }
205       return defaultValue;
206    }
207
208    public static Element JavaDoc stringToElement(String JavaDoc xml) throws Exception JavaDoc
209    {
210       ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(xml.getBytes("utf8"));
211       DocumentBuilder JavaDoc builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
212       Document JavaDoc d = builder.parse(bais);
213       bais.close();
214       return d.getDocumentElement();
215    }
216
217    public static Element JavaDoc getDocumentRoot(InputStream JavaDoc is)
218    {
219       Document JavaDoc doc = null;
220       try
221       {
222          InputSource JavaDoc xmlInp = new InputSource JavaDoc(is);
223
224          DocumentBuilderFactory JavaDoc docBuilderFactory = DocumentBuilderFactory.newInstance();
225          DocumentBuilder JavaDoc parser = docBuilderFactory.newDocumentBuilder();
226          doc = parser.parse(xmlInp);
227          Element JavaDoc root = doc.getDocumentElement();
228          root.normalize();
229          return root;
230       }
231       catch (SAXParseException JavaDoc err)
232       {
233          log.error("Configurator SAXParse error", err);
234       }
235       catch (SAXException JavaDoc e)
236       {
237          log.error("Configurator SAX error", e);
238       }
239       catch (Exception JavaDoc pce)
240       {
241          log.error("Configurator general error", pce);
242       }
243       return null;
244    }
245
246    /**
247     * Retrieves the boolean value of a given attribute for the first encountered instance of a tag in an element.
248     *
249     * @param elem
250     * @param tagName
251     * @param attributeName
252     * @param defaultValue
253     */

254    public static boolean readBooleanAttribute(Element JavaDoc elem, String JavaDoc tagName, String JavaDoc attributeName, boolean defaultValue)
255    {
256       String JavaDoc val = getAttributeValue(elem, tagName, attributeName);
257       if (val != null)
258       {
259          if (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("false"))
260          {
261             return Boolean.valueOf(val);
262          }
263       }
264
265       return defaultValue;
266    }
267
268 }
269
Popular Tags