KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > webdav > lib > util > DOMUtils


1 /*
2  * $Header: /home/cvs/jakarta-slide/webdavclient/clientlib/src/java/org/apache/webdav/lib/util/DOMUtils.java,v 1.2.2.1 2004/08/30 08:09:04 ib Exp $
3  * $Revision: 1.2.2.1 $
4  * $Date: 2004/08/30 08:09:04 $
5  *
6  * ====================================================================
7  *
8  * Copyright 1999-2002 The Apache Software Foundation
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  *
22  */

23
24 package org.apache.webdav.lib.util;
25
26 import java.util.StringTokenizer JavaDoc;
27 import java.util.Vector JavaDoc;
28
29 import org.w3c.dom.Attr JavaDoc;
30 import org.w3c.dom.Document JavaDoc;
31 import org.w3c.dom.Element JavaDoc;
32 import org.w3c.dom.NamedNodeMap JavaDoc;
33 import org.w3c.dom.Node JavaDoc;
34 import org.w3c.dom.NodeList JavaDoc;
35 import org.w3c.dom.Text JavaDoc;
36
37 /**
38  * This class provides some basic utility methods for working with
39  * XML Document objects. Many of these utilities provide JAXP 1.0 "brute
40  * force" implementations of functions that are available in JAXP 1.1.
41  *
42  * @version $Revision: 1.2.2.1 $
43  */

44 public class DOMUtils {
45
46     protected static Class JavaDoc[] getElementsByNSParameterTypes =
47         { String JavaDoc.class, String JavaDoc.class };
48
49     /**
50      * Determine the namespace prefix being used for DAV.
51      * Generally, DAV responses say something like:
52      *
53      * <PRE>
54      * &lt;D:multistatus xmlns:D="DAV:"&gt;
55      * </PRE>
56      *
57      * <P> In this case, the "D:" is the prefix for DAV.
58      * @deprecated
59      */

60     public static String JavaDoc findDavPrefix(Document JavaDoc document) {
61         Element JavaDoc multistatus = document.getDocumentElement();
62         NamedNodeMap JavaDoc list = multistatus.getAttributes();
63         String JavaDoc prefix = "DAV:";
64         for (int i = 0; i < list.getLength(); i++) {
65             try {
66                 Attr JavaDoc attr = (Attr JavaDoc) list.item(i);
67                 if (attr.getName() != null &&
68                     attr.getName().startsWith("xmlns") &&
69                     attr.getValue().equals("DAV:")) {
70                     int indx = attr.getName().indexOf(":");
71                     if ((indx >= 0) && (indx < attr.getName().length()-1)) {
72                         prefix = attr.getName().substring(indx + 1) + ":";
73                     } else {
74                         prefix = "";
75                     }
76                 }
77             } catch (ClassCastException JavaDoc e) {
78             }
79         }
80         return prefix;
81     }
82
83
84     /**
85      * Recursively scans all child elements, appending any text nodes.
86      *
87      * <PRE>
88      * &lt;customer&gt;Joe Schmoe&lt;/customer&gt;
89      * </PRE>
90      *
91      * <P> In this case, calling this method on the
92      * <CODE>customer</CODE> element returns "Joe Schmoe".
93      */

94     public static String JavaDoc getTextValue(Node JavaDoc node) {
95
96         // I *thought* that I should be able to use element.getNodeValue()...
97

98         StringBuffer JavaDoc text = new StringBuffer JavaDoc();
99         NodeList JavaDoc nodeList = node.getChildNodes();
100         for (int i = 0; i < nodeList.getLength(); i++) {
101             if (nodeList.item(i).getNodeType() == Node.TEXT_NODE
102                 || nodeList.item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
103                 text.append(((Text JavaDoc) nodeList.item(i)).getData());
104             } else {
105                 text.append(getTextValue(nodeList.item(i)));
106             }
107         }
108         return text.toString();
109     }
110
111     /**
112      * Get the status code out of the normal status response.
113      *
114      * <P> Each <code>DAV:propstat</code> node contains a
115      * status line, such as:
116      *
117      * <PRE>
118      * &lt;DAV:status&gt;HTTP/1.1 200 OK&lt;/DAV:status&gt;
119      * </PRE>
120      *
121      * <P> In this case, calling this method on the
122      * text string returns 200.
123      */

124     public static int parseStatus(String JavaDoc statusString) {
125         int status = -1;
126         if (statusString != null) {
127             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(statusString);
128             if (tokenizer.countTokens() >= 2) {
129                 tokenizer.nextElement();
130                 String JavaDoc statusCode = tokenizer.nextElement().toString();
131                 try {
132                     status = Integer.parseInt(statusCode);
133                 } catch (NumberFormatException JavaDoc e) {
134                     throw new IllegalArgumentException JavaDoc(
135                         "Status code is not numeric");
136                 }
137             } else {
138                 throw new IllegalArgumentException JavaDoc(
139                     "There aren't enough words in the input argument");
140             }
141         }
142         return status;
143     }
144
145     public static String JavaDoc getElementNamespaceURI(Element JavaDoc element) {
146         String JavaDoc namespace = null;
147
148         if (element == null) {
149             throw new IllegalArgumentException JavaDoc(
150                 "The element cannot be null");
151         } else {
152             try {
153                 namespace = element.getNamespaceURI();
154             }
155             catch (NoSuchMethodError JavaDoc e) {
156                 String JavaDoc tagName = element.getTagName();
157                 String JavaDoc attribute = "xmlns";
158                 int index = tagName.indexOf(":");
159                 if (index > 0 && index < (tagName.length()-1)) {
160                     attribute += (":" + tagName.substring(0,index));
161                 }
162
163                 boolean found = false;
164                 for (Node JavaDoc node = element; !found && node != null;
165                     node = node.getParentNode()) {
166                     try {
167                         String JavaDoc tmp = ((Element JavaDoc) node).getAttribute(attribute);
168                         if (tmp != null && !tmp.equals("")) {
169                             namespace = tmp;
170                             found = true;
171                         }
172                     }
173                     catch (ClassCastException JavaDoc f) {
174                         // this will happen for Documents
175
}
176                 }
177             }
178         }
179
180         return namespace;
181     }
182
183     public static String JavaDoc getElementLocalName(Element JavaDoc element) {
184         String JavaDoc localName = null;
185
186         if (element == null) {
187             throw new IllegalArgumentException JavaDoc(
188                 "The element cannot be null");
189         } else {
190             try {
191                 localName = element.getLocalName();
192             }
193             catch (NoSuchMethodError JavaDoc e) {
194                 localName = element.getTagName();
195                 int index = localName.indexOf(":");
196                 if (index > 0 && index < (localName.length()-1)) {
197                     localName = localName.substring(index + 1);
198                 }
199             }
200         }
201         return localName;
202     }
203
204     /**
205      *
206      */

207     public static NodeList JavaDoc getElementsByTagNameNS(
208         Node JavaDoc node, String JavaDoc tagName, String JavaDoc namespace) {
209
210         NodeList JavaDoc list = null;
211         
212         if (node == null) {
213             return null;
214         }
215         else if (!(node instanceof Document JavaDoc) && !(node instanceof Element JavaDoc)) {
216             throw new IllegalArgumentException JavaDoc(
217                     "The node parameter must be an Element or a Document node");
218         }
219         else {
220             try {
221                 list = ((Element JavaDoc) node).getElementsByTagNameNS(namespace, tagName);
222             }
223             catch (NoSuchMethodError JavaDoc e) {
224                 Vector JavaDoc vector = new Vector JavaDoc();
225                 getChildElementsByTagNameNS(vector, node, tagName, namespace);
226                 list = new NodeListImpl(vector);
227             }
228         }
229         return list;
230     }
231
232
233     protected static void getChildElementsByTagNameNS(
234         Vector JavaDoc vector, Node JavaDoc node, String JavaDoc tagName, String JavaDoc namespace) {
235
236         NodeList JavaDoc list = node.getChildNodes();
237         for (int i = 0; list != null && i < list.getLength(); i++) {
238             try {
239                 Element JavaDoc element = (Element JavaDoc) list.item(i);
240
241                 if (tagName.equals(getElementLocalName(element)) &&
242                     namespace.equals(getElementNamespaceURI(element))) {
243
244                     vector.addElement(element);
245                 } else {
246                     // RECURSIVE! DANGER, WILL ROBINSON!
247
getChildElementsByTagNameNS(vector, element,
248                                                 tagName, namespace);
249                 }
250             } catch (ClassCastException JavaDoc e) {
251             }
252         }
253     }
254
255
256     /**
257      * Get the first element matched with the given namespace and name.
258      *
259      * @param node The node.
260      * @param namespac The namespace.
261      * @param name The name.
262      * @return The wanted first element.
263      */

264     public static Element JavaDoc getFirstElement(Node JavaDoc node, String JavaDoc namespace,
265                                           String JavaDoc name) {
266         NodeList JavaDoc children = node.getChildNodes();
267         if (children == null)
268             return null;
269         for (int i = 0; i < children.getLength(); i++) {
270             try {
271                 Element JavaDoc child = (Element JavaDoc) children.item(i);
272                 if (name.equals(getElementLocalName(child)) &&
273                     namespace.equals(getElementNamespaceURI(child))) {
274                     return child;
275                 }
276             } catch (ClassCastException JavaDoc e) {
277             }
278         }
279         return null;
280     }
281
282
283     // ---------------------------------------------------------- Inner Classes
284

285
286     /**
287      * This class provides an implementation of NodeList, which is used by
288      * the getElementsByTagNameNS() method.
289      */

290     static class NodeListImpl implements NodeList JavaDoc {
291         private Vector JavaDoc vector = null;
292
293         NodeListImpl(Vector JavaDoc vector) {
294             this.vector = vector;
295         }
296
297         public int getLength() {
298             return vector.size();
299         }
300
301         public Node JavaDoc item(int i) {
302             return (Node JavaDoc) vector.elementAt(i);
303         }
304     }
305 }
306
Popular Tags