KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > commons > xml > XMLDocument


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  */

19 package org.openharmonise.commons.xml;
20
21
22 import java.io.*;
23
24 import java.util.*;
25 import java.util.logging.*;
26 import java.util.logging.Logger JavaDoc;
27
28 import javax.xml.parsers.*;
29
30
31 import org.w3c.dom.*;
32 import org.xml.sax.*;
33
34 /**
35  * This class is a Proxy implementation of the <code>org.w3c.dom.Document</code> interface
36  * which allows a single class to wrap up whatever implementation of the interface is
37  * currently used with in the Harmonise framework, and adding a couple of utility methods.
38  *
39  * @author Michael Bell
40  * @version $Revision: 1.2 $
41  *
42  */

43 public class XMLDocument implements Document {
44     
45     Document m_xml = null;
46     
47     private static final Logger JavaDoc m_logger = Logger.getLogger(XMLDocument.class.getName());
48
49     /**
50      * Constructs an XMLDocument from a w3c Document.
51      *
52      * @param document - The document to use
53      */

54     public XMLDocument() {
55         super();
56
57         DocumentBuilder docBuilder;
58
59         try {
60             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
61             factory.setNamespaceAware(true);
62             
63             docBuilder = factory.newDocumentBuilder();
64         }
65         catch (ParserConfigurationException e) {
66             throw new DocumentInstantiationException("Parser configuration exception", e);
67         }
68         catch (FactoryConfigurationError e) {
69             throw new DocumentInstantiationException("Factory configuration exception", e);
70         }
71
72         m_xml = docBuilder.newDocument();
73     }
74
75     /**
76      * Constructs an XMLDocument from a w3c Document.
77      *
78      * @param document - The document to use
79      */

80     public XMLDocument(org.w3c.dom.Document JavaDoc document) {
81         // copy the root of the document to here
82
m_xml= document;
83     }
84
85     /** Returns a copy of the given node, copied to this document.
86      *
87      * @param originalEl Node to be copied
88      */

89     public Node copyNode(Node originalEl) {
90         int i = 0;
91
92         Node returnNode = null;
93
94         if (originalEl.getNodeType() == Node.ELEMENT_NODE) {
95             Element el = createElement(((Element) originalEl).getTagName());
96             NamedNodeMap attribs = originalEl.getAttributes();
97
98             for (i = 0; i < attribs.getLength(); i++) {
99                 Attr nextAtt = (Attr) attribs.item(i);
100                 el.setAttribute(nextAtt.getNodeName(), nextAtt.getValue());
101             }
102
103             NodeList nodes = originalEl.getChildNodes();
104
105             for (i = 0; i < nodes.getLength(); i++) {
106                 if ((nodes.item(i).getNodeType() == Node.ELEMENT_NODE)
107                     || (nodes.item(i).getNodeType() == Node.TEXT_NODE)) {
108                     el.appendChild(copyNode(nodes.item(i)));
109                 }
110             }
111
112             returnNode = (Node) el;
113         } else if (originalEl.getNodeType() == Node.TEXT_NODE) {
114             Text el = createTextNode(originalEl.getNodeValue());
115
116             returnNode = (Node) el;
117         }
118
119         return returnNode;
120     }
121
122     /** Copies XML child nodes from parent source to parent_destination element in this document.
123      *
124      * @param parent_destination Element to have child nodes copied to
125      * @param parent_source Element with child nodes to be copied
126      * @param destination_xml_document XML document containing
127      * parent_destination
128      */

129     public void copyChildren(
130         Element parent_destination,
131         Element parent_source) {
132         copyChildren(parent_destination, parent_source, new Vector());
133     }
134
135     /** Copies XML child nodes from parent source to parent_destination element.
136      *
137      * @param parent_destination Element to have child nodes copied to
138      * @param parent_source Element with child nodes to be copied
139      * @param destination_xml_document XML document containing
140      * parent_destination
141      * @param ignoreTags List of node names to be ignored (not copied over)
142      */

143     public void copyChildren(
144         Element parent_destination,
145         Element parent_source,
146         Vector ignoreTags) {
147         // copy all caption nodes (if any exist)
148
NodeList child_nodes = parent_source.getChildNodes();
149
150         for (int k = 0; k < child_nodes.getLength(); k++) {
151             if ((child_nodes.item(k).getNodeType() == Node.ELEMENT_NODE)
152                 && ignoreTags.contains(
153                     ((Element) child_nodes.item(k)).getTagName())) {
154                 continue;
155             }
156
157             Node node = child_nodes.item(k);
158
159             if (node != null) {
160                 parent_destination.appendChild(this.copyNode(node));
161             }
162         }
163     }
164
165     /** Convenience method to display top form element, for logging purposes only.
166     *
167     * @param element The element to display info for
168     */

169     public static String JavaDoc elementInfo(Element element) {
170         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
171         strbuf.append("<").append(element.getTagName());
172
173         NamedNodeMap attributes = element.getAttributes();
174
175         for (int i = 0; i < attributes.getLength(); i++) {
176             strbuf
177                 .append(" ")
178                 .append(((Attr) attributes.item(i)).getName())
179                 .append("=\"")
180                 .append(((Attr) attributes.item(i)).getValue())
181                 .append("\"");
182         }
183
184         if (element.getChildNodes().getLength() == 0) {
185             strbuf.append("/>");
186         } else {
187             strbuf.append("> ...");
188         }
189
190         return strbuf.toString();
191     }
192
193     /**
194      * Compares the two given elements and returns <code>true</code> if they match.
195      *
196      * @param origEl
197      * @param compEl
198      * @return
199      */

200     public static boolean compareElement(Element origEl, Element compEl) {
201         boolean bMatch = true;
202
203         if (compEl.getTagName().equals(origEl.getTagName()) == false) {
204             bMatch = false;
205         } else {
206             //match attributes
207
NamedNodeMap primAttribs = origEl.getAttributes();
208             int i = 0;
209
210             while ((i < primAttribs.getLength()) && (bMatch == true)) {
211                 Attr attrib = (Attr) primAttribs.item(i);
212
213                 String JavaDoc compareValue = compEl.getAttribute(attrib.getName());
214                 String JavaDoc origValue = attrib.getNodeValue();
215
216                 if (compareValue.equals(origValue) == false) {
217                     bMatch = false;
218                 }
219
220                 i++;
221             }
222
223             if (bMatch == true) {
224                 //match elements
225
NodeList origChildren = origEl.getChildNodes();
226                 NodeList compChildren = compEl.getChildNodes();
227
228                 //quick rough comparison
229
if (origChildren.getLength() != compChildren.getLength()) {
230                     bMatch = false;
231                 }
232
233                 if ((bMatch == true) && (origChildren.getLength() > 0)) {
234                     i = 0;
235
236                     while ((i < origChildren.getLength())
237                         && (bMatch == true)) {
238                         if (origChildren.item(i).getNodeType()
239                             == Node.ELEMENT_NODE) {
240                             Element origChild = (Element) origChildren.item(i);
241
242                             Element compChild =
243                                 (Element) compEl.getElementsByTagName(
244                                     origChild.getTagName()).item(
245                                     0);
246
247                             bMatch = compareElement(origChild, compChild);
248                         }
249
250                         i++;
251                     }
252                 }
253             }
254         }
255
256         return bMatch;
257     }
258
259     /** Takes XML node and prints to String.
260       *
261       * @param node Element to print to String
262       * @return XML node as String
263       */

264     public static String JavaDoc printNode(Node node) {
265         StringBuffer JavaDoc sBuffer = new StringBuffer JavaDoc();
266
267         if (node.getNodeType() == Node.TEXT_NODE) {
268             sBuffer.append(node.getNodeValue());
269         } else if (node.getNodeType() == Node.CDATA_SECTION_NODE) {
270             sBuffer.append("<![CDATA[");
271             sBuffer.append(node.getNodeValue());
272             sBuffer.append("]]>");
273         } else if (node.getNodeType() == Node.ELEMENT_NODE) {
274             Element el = (Element) node;
275
276             sBuffer.append("<" + el.getTagName());
277
278             NamedNodeMap attribs = el.getAttributes();
279
280             for (int i = 0; i < attribs.getLength(); i++) {
281                 Attr nextAtt = (Attr) attribs.item(i);
282                 sBuffer.append(
283                     " "
284                         + nextAtt.getName()
285                         + "=\""
286                         + nextAtt.getValue()
287                         + "\"");
288             }
289
290             NodeList nodes = node.getChildNodes();
291
292             if (nodes.getLength() == 0) {
293                 sBuffer.append("/>");
294             } else {
295                 sBuffer.append(">");
296
297                 for (int i = 0; i < nodes.getLength(); i++) {
298                     sBuffer.append(printNode(nodes.item(i)));
299                 }
300
301                 sBuffer.append("</" + el.getTagName() + ">");
302             }
303         }
304
305         return (sBuffer.toString());
306     }
307
308     /**
309     * Finds element in one element which matches the another element.
310     *
311     * @param el Element to match
312     * @param state XML representation
313     * @return Matching Element found
314     */

315     static public Element findElement(Element sourceEl, Element toFindEl) {
316         Element foundEl = null;
317         String JavaDoc sTagName = toFindEl.getTagName();
318
319         NodeList nodes = sourceEl.getChildNodes();
320
321         String JavaDoc sFindName = toFindEl.getAttribute("name");
322         String JavaDoc sFindId = toFindEl.getAttribute("id");
323
324         for (int i = 0; i < nodes.getLength(); i++) {
325             if (nodes.item(i).getNodeType() != Node.ELEMENT_NODE) {
326                 continue;
327             }
328
329             Element next = (Element) nodes.item(i);
330             String JavaDoc sNextName = next.getAttribute("name");
331             String JavaDoc sNextId = next.getAttribute("id");
332
333             boolean bFoundName = false;
334             boolean bFoundId = false;
335
336             if (sTagName.equalsIgnoreCase(next.getTagName())) {
337                 if (!sFindName.equalsIgnoreCase("")
338                     && !sNextName.equalsIgnoreCase("")) {
339                     if (sFindName.equals(sNextName)) {
340                         bFoundName = true;
341                     }
342                 } else {
343                     bFoundName = true;
344                 }
345
346                 if (!sFindId.equalsIgnoreCase("")
347                     && !sNextId.equalsIgnoreCase("")) {
348                     if (sFindId.equals(sNextId)) {
349                         bFoundId = true;
350                     }
351                 } else {
352                     bFoundId = true;
353                 }
354             }
355
356             if (bFoundId && bFoundName) {
357                 foundEl = next;
358             } else if (next.hasChildNodes()) {
359                 foundEl = findElement(next, toFindEl);
360             }
361
362             if (foundEl != null) {
363                 break;
364             }
365         }
366
367         return foundEl;
368     }
369
370     /**
371      * Returns the <code>String</code> value of the <code>Text</code> <code>Node</code>
372      * which is a child of the given element.
373      *
374      * @param xmlElement
375      * @return
376      */

377     static public String JavaDoc getChildTextNodeValue(Element xmlElement) {
378         Text txt = null;
379
380         try {
381             txt = (Text) xmlElement.getFirstChild();
382         } catch (ClassCastException JavaDoc e) {
383             m_logger.log(Level.WARNING, e.getLocalizedMessage(),e);
384         }
385
386         if (txt != null) {
387             return (txt.getNodeValue());
388         } else {
389             return "";
390         }
391     }
392
393     /**
394      * Returns <code>org.w3c.dom.Document</code> from the given <code>String</code>.
395      *
396      * @param sXML
397      * @return
398      * @throws SAXException
399      * @throws IOException
400      * @throws ParserConfigurationException
401      * @throws FactoryConfigurationError
402      */

403     static public org.w3c.dom.Document JavaDoc getXMLDocumentFromString(String JavaDoc sXML)
404         throws
405             SAXException,
406             IOException,
407             ParserConfigurationException,
408             FactoryConfigurationError {
409         
410         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
411         factory.setNamespaceAware(true);
412         return (
413                 factory.newDocumentBuilder().parse(
414                 new org.xml.sax.InputSource JavaDoc(new StringReader(sXML))));
415     }
416
417     /* (non-Javadoc)
418      * @see java.lang.Object#hashCode()
419      */

420     public int hashCode() {
421         return m_xml.hashCode();
422     }
423
424     /* (non-Javadoc)
425      * @see java.lang.Object#equals(java.lang.Object)
426      */

427     public boolean equals(Object JavaDoc arg0) {
428         return m_xml.equals(arg0);
429     }
430
431     /* (non-Javadoc)
432      * @see java.lang.Object#toString()
433      */

434     public String JavaDoc toString() {
435         return m_xml.toString();
436     }
437
438     /* (non-Javadoc)
439      * @see org.w3c.dom.Node#cloneNode(boolean)
440      */

441     public Node cloneNode(boolean arg0) {
442         return m_xml.cloneNode(arg0);
443     }
444
445     /* (non-Javadoc)
446      * @see org.w3c.dom.Node#getChildNodes()
447      */

448     public NodeList getChildNodes() {
449         return m_xml.getChildNodes();
450     }
451
452     /* (non-Javadoc)
453      * @see org.w3c.dom.Document#getElementsByTagName(java.lang.String)
454      */

455     public NodeList getElementsByTagName(String JavaDoc arg0) {
456         return m_xml.getElementsByTagName(arg0);
457     }
458
459     /* (non-Javadoc)
460      * @see org.w3c.dom.Document#createAttribute(java.lang.String)
461      */

462     public Attr createAttribute(String JavaDoc arg0) throws DOMException {
463         return m_xml.createAttribute(arg0);
464     }
465
466     /* (non-Javadoc)
467      * @see org.w3c.dom.Node#getAttributes()
468      */

469     public NamedNodeMap getAttributes() {
470         return m_xml.getAttributes();
471     }
472
473     /* (non-Javadoc)
474      * @see org.w3c.dom.Node#setPrefix(java.lang.String)
475      */

476     public void setPrefix(String JavaDoc arg0) throws DOMException {
477         m_xml.setPrefix(arg0);
478     }
479
480     /* (non-Javadoc)
481      * @see org.w3c.dom.Document#createComment(java.lang.String)
482      */

483     public Comment createComment(String JavaDoc arg0) {
484         return m_xml.createComment(arg0);
485     }
486
487     /* (non-Javadoc)
488      * @see org.w3c.dom.Document#createEntityReference(java.lang.String)
489      */

490     public EntityReference createEntityReference(String JavaDoc arg0)
491         throws DOMException {
492         return m_xml.createEntityReference(arg0);
493     }
494
495     /* (non-Javadoc)
496      * @see org.w3c.dom.Node#insertBefore(org.w3c.dom.Node, org.w3c.dom.Node)
497      */

498     public Node insertBefore(Node arg0, Node arg1) throws DOMException {
499         return m_xml.insertBefore(arg0, arg1);
500     }
501
502     /* (non-Javadoc)
503      * @see org.w3c.dom.Node#getLastChild()
504      */

505     public Node getLastChild() {
506         return m_xml.getLastChild();
507     }
508
509     /* (non-Javadoc)
510      * @see org.w3c.dom.Node#replaceChild(org.w3c.dom.Node, org.w3c.dom.Node)
511      */

512     public Node replaceChild(Node arg0, Node arg1) throws DOMException {
513         return m_xml.replaceChild(arg0, arg1);
514     }
515
516     /* (non-Javadoc)
517      * @see org.w3c.dom.Document#createAttributeNS(java.lang.String, java.lang.String)
518      */

519     public Attr createAttributeNS(String JavaDoc arg0, String JavaDoc arg1)
520         throws DOMException {
521         return m_xml.createAttributeNS(arg0, arg1);
522     }
523
524     /* (non-Javadoc)
525      * @see org.w3c.dom.Document#createElementNS(java.lang.String, java.lang.String)
526      */

527     public Element createElementNS(String JavaDoc arg0, String JavaDoc arg1)
528         throws DOMException {
529         return m_xml.createElementNS(arg0, arg1);
530     }
531
532     /* (non-Javadoc)
533      * @see org.w3c.dom.Node#getPrefix()
534      */

535     public String JavaDoc getPrefix() {
536         return m_xml.getPrefix();
537     }
538
539     /* (non-Javadoc)
540      * @see org.w3c.dom.Node#getOwnerDocument()
541      */

542     public Document getOwnerDocument() {
543         return m_xml.getOwnerDocument();
544     }
545
546     /* (non-Javadoc)
547      * @see org.w3c.dom.Node#getNodeType()
548      */

549     public short getNodeType() {
550         return m_xml.getNodeType();
551     }
552
553     /* (non-Javadoc)
554      * @see org.w3c.dom.Document#getDocumentElement()
555      */

556     public Element getDocumentElement() {
557         return m_xml.getDocumentElement();
558     }
559
560     /* (non-Javadoc)
561      * @see org.w3c.dom.Document#createElement(java.lang.String)
562      */

563     public Element createElement(String JavaDoc arg0) throws DOMException {
564         return m_xml.createElement(arg0);
565     }
566
567     /* (non-Javadoc)
568      * @see org.w3c.dom.Document#createCDATASection(java.lang.String)
569      */

570     public CDATASection createCDATASection(String JavaDoc arg0) throws DOMException {
571         return m_xml.createCDATASection(arg0);
572     }
573
574     /* (non-Javadoc)
575      * @see org.w3c.dom.Document#importNode(org.w3c.dom.Node, boolean)
576      */

577     public Node importNode(Node arg0, boolean arg1) throws DOMException {
578         return m_xml.importNode(arg0, arg1);
579     }
580
581     /* (non-Javadoc)
582      * @see org.w3c.dom.Node#getNamespaceURI()
583      */

584     public String JavaDoc getNamespaceURI() {
585         return m_xml.getNamespaceURI();
586     }
587
588     /* (non-Javadoc)
589      * @see org.w3c.dom.Node#getPreviousSibling()
590      */

591     public Node getPreviousSibling() {
592         return m_xml.getPreviousSibling();
593     }
594
595     /* (non-Javadoc)
596      * @see org.w3c.dom.Document#getDoctype()
597      */

598     public DocumentType getDoctype() {
599         return m_xml.getDoctype();
600     }
601
602     /* (non-Javadoc)
603      * @see org.w3c.dom.Node#getFirstChild()
604      */

605     public Node getFirstChild() {
606         return m_xml.getFirstChild();
607     }
608
609     /* (non-Javadoc)
610      * @see org.w3c.dom.Node#getParentNode()
611      */

612     public Node getParentNode() {
613         return m_xml.getParentNode();
614     }
615
616     /* (non-Javadoc)
617      * @see org.w3c.dom.Node#isSupported(java.lang.String, java.lang.String)
618      */

619     public boolean isSupported(String JavaDoc arg0, String JavaDoc arg1) {
620         return m_xml.isSupported(arg0, arg1);
621     }
622
623     /* (non-Javadoc)
624      * @see org.w3c.dom.Document#getElementById(java.lang.String)
625      */

626     public Element getElementById(String JavaDoc arg0) {
627         return m_xml.getElementById(arg0);
628     }
629
630     /* (non-Javadoc)
631      * @see org.w3c.dom.Document#createTextNode(java.lang.String)
632      */

633     public Text createTextNode(String JavaDoc arg0) {
634         return m_xml.createTextNode(arg0);
635     }
636
637     /* (non-Javadoc)
638      * @see org.w3c.dom.Document#createDocumentFragment()
639      */

640     public DocumentFragment createDocumentFragment() {
641         return m_xml.createDocumentFragment();
642     }
643
644     /* (non-Javadoc)
645      * @see org.w3c.dom.Node#setNodeValue(java.lang.String)
646      */

647     public void setNodeValue(String JavaDoc arg0) throws DOMException {
648         m_xml.setNodeValue(arg0);
649     }
650
651     /* (non-Javadoc)
652      * @see org.w3c.dom.Document#getImplementation()
653      */

654     public DOMImplementation getImplementation() {
655         return m_xml.getImplementation();
656     }
657
658     /* (non-Javadoc)
659      * @see org.w3c.dom.Node#appendChild(org.w3c.dom.Node)
660      */

661     public Node appendChild(Node arg0) throws DOMException {
662         return m_xml.appendChild(arg0);
663     }
664
665     /* (non-Javadoc)
666      * @see org.w3c.dom.Document#getElementsByTagNameNS(java.lang.String, java.lang.String)
667      */

668     public NodeList getElementsByTagNameNS(String JavaDoc arg0, String JavaDoc arg1) {
669         return m_xml.getElementsByTagNameNS(arg0, arg1);
670     }
671
672     /* (non-Javadoc)
673      * @see org.w3c.dom.Document#createProcessingInstruction(java.lang.String, java.lang.String)
674      */

675     public ProcessingInstruction createProcessingInstruction(
676         String JavaDoc arg0,
677         String JavaDoc arg1)
678         throws DOMException {
679         return m_xml.createProcessingInstruction(arg0, arg1);
680     }
681
682     /* (non-Javadoc)
683      * @see org.w3c.dom.Node#getNodeValue()
684      */

685     public String JavaDoc getNodeValue() throws DOMException {
686         return m_xml.getNodeValue();
687     }
688
689     /* (non-Javadoc)
690      * @see org.w3c.dom.Node#removeChild(org.w3c.dom.Node)
691      */

692     public Node removeChild(Node arg0) throws DOMException {
693         return m_xml.removeChild(arg0);
694     }
695
696     /* (non-Javadoc)
697      * @see org.w3c.dom.Node#hasAttributes()
698      */

699     public boolean hasAttributes() {
700         return m_xml.hasAttributes();
701     }
702
703     /* (non-Javadoc)
704      * @see org.w3c.dom.Node#getNextSibling()
705      */

706     public Node getNextSibling() {
707         return m_xml.getNextSibling();
708     }
709
710     /* (non-Javadoc)
711      * @see org.w3c.dom.Node#normalize()
712      */

713     public void normalize() {
714         m_xml.normalize();
715     }
716
717     /* (non-Javadoc)
718      * @see org.w3c.dom.Node#getLocalName()
719      */

720     public String JavaDoc getLocalName() {
721         return m_xml.getLocalName();
722     }
723
724     /* (non-Javadoc)
725      * @see org.w3c.dom.Node#hasChildNodes()
726      */

727     public boolean hasChildNodes() {
728         return m_xml.hasChildNodes();
729     }
730
731     /* (non-Javadoc)
732      * @see org.w3c.dom.Node#getNodeName()
733      */

734     public String JavaDoc getNodeName() {
735         return m_xml.getNodeName();
736     }
737
738 }
Popular Tags