KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mullassery > act > util > XMLUtil


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if
20  * any, must include the following acknowlegement:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowlegement may appear in the software itself,
24  * if and wherever such third-party acknowlegements normally appear.
25  *
26  * 4. The names "The Jakarta Project", "Ant", and "Apache Software
27  * Foundation" must not be used to endorse or promote products derived
28  * from this software without prior written permission. For written
29  * permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache"
32  * nor may "Apache" appear in their names without prior written
33  * permission of the Apache Group.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation. For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  */

54
55 package com.mullassery.act.util;
56
57 import java.io.BufferedWriter JavaDoc;
58 import java.io.File JavaDoc;
59 import java.io.FileWriter JavaDoc;
60 import java.io.InputStream JavaDoc;
61 import java.util.HashMap JavaDoc;
62 import java.util.Iterator JavaDoc;
63 import java.util.StringTokenizer JavaDoc;
64 import java.util.Vector JavaDoc;
65
66 import javax.xml.parsers.DocumentBuilder JavaDoc;
67 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
68
69 import org.apache.tools.ant.util.DOMElementWriter;
70 import org.w3c.dom.Document JavaDoc;
71 import org.w3c.dom.Element JavaDoc;
72 import org.w3c.dom.NamedNodeMap JavaDoc;
73 import org.w3c.dom.Node JavaDoc;
74 import org.w3c.dom.NodeList JavaDoc;
75
76 import com.mullassery.act.ACTException;
77 import com.mullassery.act.TaskMaster;
78
79 /**
80  *
81  * @author Abey Mullassery
82  *
83  */

84 public class XMLUtil {
85
86     /** Creates a new instance of XMLUtil */
87     private XMLUtil() {
88     }
89
90     public static void cleanText(Node JavaDoc node) {
91         try {
92             NodeList JavaDoc childNodes = node.getChildNodes();
93             int noChildren = childNodes.getLength();
94             Node JavaDoc n = null;
95             short type = 0;
96             Vector JavaDoc rem = new Vector JavaDoc();
97             for (int i = 0; i < noChildren; i++) {
98                 n = childNodes.item(i);
99                 type = n.getNodeType();
100                 if (type == Node.TEXT_NODE) {
101                     rem.add(n);
102                 } else if (type == Node.ELEMENT_NODE) {
103                     cleanText(n);
104                 }
105             }
106             for (int i = 0; i < rem.size(); i++) {
107                 node.removeChild((Node JavaDoc) rem.get(i));
108             }
109         } catch (Exception JavaDoc e) {
110             //DebugUtil.debug(e);
111
}
112     }
113
114     public static boolean compareElements(Element JavaDoc e1, Element JavaDoc e2) {
115         if (e1.equals(e2))
116             return true;
117         Document JavaDoc doc = e1.getOwnerDocument();
118         e2 = (Element JavaDoc) doc.importNode(e2, true);
119         return e1.equals(e2);
120     }
121
122     public static Element JavaDoc findElementNode(
123         Node JavaDoc root,
124         String JavaDoc elementName,
125         boolean deep) {
126         return (Element JavaDoc) findNode(root, elementName, deep, true);
127
128     }
129
130     public static Node JavaDoc findNode(Node JavaDoc root, String JavaDoc elementName, boolean deep) {
131         return findNode(root, elementName, deep, false);
132     }
133
134     public static Node JavaDoc findNode(
135         Node JavaDoc root,
136         String JavaDoc elementName,
137         boolean deep,
138         boolean elementsOnly) {
139         //Check to see if root has any children if not return null
140
if (!(root.hasChildNodes()))
141             return null;
142
143         //Root has children, so continue searching for them
144
Node JavaDoc matchingNode = null;
145         String JavaDoc nodeName = null;
146         Node JavaDoc child = null;
147
148         NodeList JavaDoc childNodes = root.getChildNodes();
149         int noChildren = childNodes.getLength();
150         for (int i = 0; i < noChildren; i++) {
151             if (matchingNode == null) {
152                 child = childNodes.item(i);
153                 nodeName = child.getNodeName();
154                 if ((nodeName != null) & (nodeName.equals(elementName)))
155                     return child;
156                 if (deep)
157                     matchingNode =
158                         findNode(child, elementName, deep, elementsOnly);
159             } else
160                 break;
161         }
162
163         if (!elementsOnly) {
164             NamedNodeMap JavaDoc childAttrs = root.getAttributes();
165             noChildren = childAttrs.getLength();
166             for (int i = 0; i < noChildren; i++) {
167                 if (matchingNode == null) {
168                     child = childAttrs.item(i);
169                     nodeName = child.getNodeName();
170                     if ((nodeName != null) & (nodeName.equals(elementName)))
171                         return child;
172                 } else
173                     break;
174             }
175         }
176         return matchingNode;
177     }
178
179     public static Element JavaDoc getChildElement(Element JavaDoc parent, String JavaDoc childName)
180         throws ACTException {
181         Node JavaDoc n = XMLUtil.findElementNode(parent, childName, false);
182         if (n == null || n.getNodeType() != Node.ELEMENT_NODE) {
183             return (Element JavaDoc) parent.appendChild(
184                 parent.getOwnerDocument().createElement(childName));
185         } else {
186             return (Element JavaDoc) n;
187         }
188     }
189
190     /**
191      * Returns a default DocumentBuilder instance or throws an
192      * ExceptionInInitializerError if it can't be created.
193      *
194      * @return a default DocumentBuilder instance.
195      */

196     public static DocumentBuilder JavaDoc getDocumentBuilder() throws ACTException {
197         try {
198             DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
199             dbf.setIgnoringComments(true);
200             dbf.setCoalescing(true);
201             dbf.setIgnoringElementContentWhitespace(true);
202             dbf.setValidating(false);
203             return dbf.newDocumentBuilder();
204         } catch (Exception JavaDoc exc) {
205             throw new ACTException(exc.getMessage());
206         }
207     }
208
209     public static Element JavaDoc getDocumentElement(File JavaDoc fileName)
210         throws ACTException {
211         try {
212             Document JavaDoc doc = getDocumentBuilder().parse(fileName);
213             return doc.getDocumentElement();
214         } catch (Exception JavaDoc se) {
215             return null;
216         }
217     }
218
219     /**
220      * checks only attributes and sub elements
221      * @param n1
222      * @param n2
223      * @param deep
224      * @return
225      */

226     public static boolean isSame(Node JavaDoc n1, Node JavaDoc n2, boolean deep) {
227         if (n1 == null && n2 != null)
228             return false;
229         if (n1 != null && n2 == null)
230             return false;
231         if (!(n1.getNodeName().equals(n2.getNodeName())))
232             return false;
233
234         short s1 = n1.getNodeType();
235         short s2 = n2.getNodeType();
236         if (s1 != s2)
237             return false;
238         //no more checking for text nodes, etc.
239
if (!(s1 == Node.ATTRIBUTE_NODE || s1 == Node.ELEMENT_NODE))
240             return true;
241         if (s1 == Node.ATTRIBUTE_NODE) {
242             String JavaDoc v1 = n1.getNodeValue();
243             String JavaDoc v2 = n2.getNodeValue();
244             if (v1 != null && v2 != null && !v1.equals(v2))
245                 return false;
246             else
247                 return true;
248         }
249
250         Node JavaDoc t1, t2 = null;
251         //comparing attributes
252
NamedNodeMap JavaDoc nm1 = n1.getAttributes();
253         NamedNodeMap JavaDoc nm2 = n2.getAttributes();
254         if (nm1 != null && nm2 != null && nm1.getLength() != nm2.getLength())
255             return false;
256         for (int i = 0; i < nm1.getLength(); i++) {
257             t1 = nm1.item(i);
258             t2 = findNode(n2, t1.getNodeName(), false);
259             if (!isSame(t1, t2, false))
260                 return false;
261         }
262         if (!deep)
263             return true;
264
265         //comparing elements
266
NodeList JavaDoc nl1 = n1.getChildNodes();
267         NodeList JavaDoc nl2 = n2.getChildNodes();
268         if (nl1.getLength() != nl2.getLength())
269             return false;
270         for (int i = 0; i < nl1.getLength(); i++) {
271             t1 = nl1.item(i);
272             t2 = findNode(n2, t1.getNodeName(), false);
273             if (!isSame(t1, t2, true))
274                 return false;
275         }
276         return true;
277     }
278
279     public static Element JavaDoc loadDocument(File JavaDoc f, String JavaDoc defElement)
280         throws ACTException {
281         Document JavaDoc doc = null;
282         try {
283             doc = getDocumentBuilder().parse(f);
284             return doc.getDocumentElement();
285         } catch (Exception JavaDoc se) {
286             if (defElement != null)
287                 return getDocumentBuilder().newDocument().createElement(
288                     defElement);
289             throw new ACTException(se.getMessage());
290         }
291     }
292
293     public static Element JavaDoc loadDocument(InputStream JavaDoc in, String JavaDoc defElement)
294         throws ACTException {
295         Document JavaDoc doc = null;
296         try {
297             doc = getDocumentBuilder().parse(in);
298             return doc.getDocumentElement();
299         } catch (Exception JavaDoc se) {
300             if (defElement != null)
301                 return getDocumentBuilder().newDocument().createElement(
302                     defElement);
303             throw new ACTException(se.getMessage());
304         }
305     }
306
307     // private static String matchAttribute(final Iterator en, final String str)
308
// throws ACTException {
309
// String obj, match = null;
310
// while (en.hasNext()) {
311
// obj = en.next().toString();
312
// if (obj.startsWith(str)) {
313
// if (obj.equals(str)) {
314
// match = obj;
315
// break; //a full match; cannot be a conflict
316
// }
317
// if (match != null)
318
// throw new ACTException(
319
// "Parameter \""
320
// + str
321
// + "\" is ambigious since it matches with \""
322
// + match
323
// + "\" and \""
324
// + obj
325
// + "\".");
326
// match = obj;
327
// }
328
// }
329
// if (match == null)
330
// throw new ACTException(
331
// "Parameter " + str + " does not match any property.");
332
// return match;
333
// }
334

335     private static String JavaDoc match(Iterator JavaDoc en, String JavaDoc find) throws ACTException {
336         String JavaDoc obj, match = null;
337         while (en.hasNext()) {
338             obj = en.next().toString();
339             if (obj.startsWith(find)) {
340                 if (obj.equals(find)) {
341                     match = obj;
342                     break; //a full match; cannot be a conflict
343
}
344                 if (match != null)
345                     throw new ACTException(
346                         "Parameter \""
347                             + find
348                             + "\" is ambigious since it matches with \""
349                             + match
350                             + "\" and \""
351                             + obj
352                             + "\"!!");
353                 match = obj;
354             }
355         }
356         if (match == null)
357             throw new ACTException(
358                 "Parameter " + find + " does not match any element!");
359         return match;
360     }
361
362     public static void printTree(Node JavaDoc doc) {
363         if (doc == null) {
364             DebugUtil.debug("Nothing to print!!");
365             return;
366         }
367         try {
368             DebugUtil.debug(doc.getNodeName() + " " + doc.getNodeValue());
369             NamedNodeMap JavaDoc cl = doc.getAttributes();
370             for (int x = 0; x < cl.getLength(); x++) {
371                 Node JavaDoc node = cl.item(x);
372                 DebugUtil.debug(
373                     "\t" + node.getNodeName() + " ->" + node.getNodeValue());
374             }
375             NodeList JavaDoc nl = doc.getChildNodes();
376             for (int x = 0; x < nl.getLength(); x++) {
377                 Node JavaDoc node = nl.item(x);
378                 printTree(node);
379             }
380         } catch (Throwable JavaDoc e) {
381             DebugUtil.debug("Cannot print!! " + e.getMessage());
382         }
383     }
384
385     public static void saveElement(Element JavaDoc doc, File JavaDoc sFile, boolean append)
386         throws ACTException {
387         if (doc == null)
388             return;
389         BufferedWriter JavaDoc bw = null;
390         try {
391             if (!sFile.exists())
392                 sFile.createNewFile();
393             bw =
394                 new BufferedWriter JavaDoc(
395                     new FileWriter JavaDoc(sFile.getAbsolutePath(), append));
396             cleanText(doc);
397             doc.normalize();
398             new DOMElementWriter().write(doc, bw, 0, "\t");
399         } catch (Exception JavaDoc ex) {
400             throw new ACTException("Error writing to file. " + ex.getMessage());
401         } finally {
402             try {
403                 bw.flush();
404                 bw.close();
405             } catch (Exception JavaDoc e) {
406             }
407         }
408     }
409
410     public static void setProperty(
411         HashMap JavaDoc cm,
412         Element JavaDoc ep,
413         String JavaDoc str,
414         String JavaDoc value)
415         throws ACTException {
416
417         // Class taskClass = tr.getElementClass(ep.getNodeName());
418
// HashMap cm = (HashMap) TaskMaster.getElementInfo(taskClass);
419

420         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(str, ".");
421         String JavaDoc match;
422         do {
423             if (st.countTokens() == 1) { //last token?
424
match = match(cm.keySet().iterator(), st.nextToken());
425             } else {
426                 cm = (HashMap JavaDoc) cm.get(TaskMaster.CHILDREN);
427                 match = match(cm.keySet().iterator(), st.nextToken());
428                 ep = XMLUtil.getChildElement(ep, match);
429                 cm = TaskMaster.getElementInfo((Class JavaDoc) cm.get(match));
430             }
431         } while (st.hasMoreTokens());
432         ep.setAttribute(match, value);
433     }
434
435 }
436
Popular Tags