(no commit message)
[utils] / support / src / main / java / org / wamblee / xml / DomUtils.java
1 /*
2  * Copyright 2005 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.wamblee.xml;
18
19 import java.io.ByteArrayInputStream;
20 import java.io.ByteArrayOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.TreeMap;
28
29 import javax.xml.XMLConstants;
30 import javax.xml.parsers.DocumentBuilder;
31 import javax.xml.parsers.DocumentBuilderFactory;
32 import javax.xml.parsers.ParserConfigurationException;
33 import javax.xml.transform.stream.StreamSource;
34 import javax.xml.validation.Schema;
35 import javax.xml.validation.SchemaFactory;
36
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39 import org.apache.xml.serialize.OutputFormat;
40 import org.apache.xml.serialize.XMLSerializer;
41 import org.dom4j.DocumentException;
42 import org.dom4j.io.DOMReader;
43 import org.dom4j.io.DOMWriter;
44 import org.w3c.dom.Attr;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.Element;
47 import org.w3c.dom.NamedNodeMap;
48 import org.w3c.dom.Node;
49 import org.w3c.dom.NodeList;
50 import org.xml.sax.SAXException;
51
52 /**
53  * Some basic XML utilities for common reoccuring tasks for DOM documents.
54  */
55 public final class DomUtils {
56
57     private static final Log LOG = LogFactory.getLog(DomUtils.class);
58
59     /**
60      * Disabled default constructor.
61      * 
62      */
63     private DomUtils() {
64         // Empty.
65     }
66
67     /**
68      * Parses an XML document from a string.
69      * 
70      * @param aDocument
71      *            document.
72      * @return
73      */
74     public static Document read(String aDocument) throws XMLException {
75         ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes());
76         return read(is);
77     }
78
79     /**
80      * Parses an XML document from a stream.
81      * 
82      * @param aIs
83      *            Input stream.
84      * @return
85      */
86     public static Document read(InputStream aIs) throws XMLException {
87         try {
88             DocumentBuilder builder = DocumentBuilderFactory.newInstance()
89                     .newDocumentBuilder();
90             return builder.parse(aIs);
91         }  catch (SAXException e) {
92             throw new XMLException(e.getMessage(), e);
93         } catch (IOException e) {
94             throw new XMLException(e.getMessage(), e);
95         } catch (ParserConfigurationException e) {
96             throw new XMLException(e.getMessage(), e);
97         } finally {
98             try {
99                 aIs.close();
100             } catch (Exception e) {
101                 LOG.warn("Error closing XML file", e);
102             }
103         }
104     }
105
106     /**
107      * Reads and validates a document against a schema.
108      * 
109      * @param aIs
110      *            Input stream.
111      * @param aSchema
112      *            Schema.
113      * @return Parsed and validated document.
114      */
115     public static Document readAndValidate(InputStream aIs, InputStream aSchema)
116             throws XMLException {
117
118         try {
119             final Schema schema = SchemaFactory.newInstance(
120                     XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
121                     new StreamSource(aSchema));
122
123             final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
124             factory.setValidating(true);
125             factory.setNamespaceAware(true);
126             factory.setSchema(schema);
127
128             return factory.newDocumentBuilder().parse(aIs);
129         } catch (SAXException e) {
130             throw new XMLException(e.getMessage(), e);
131         } catch (IOException e) {
132             throw new XMLException(e.getMessage(), e);
133         } catch (ParserConfigurationException e) {
134             throw new XMLException(e.getMessage(), e);
135         } finally {
136             try {
137                 aSchema.close();
138             } catch (Exception e) {
139                 LOG.warn("Error closing schema", e);
140             }
141             try {
142                 aIs.close();
143             } catch (Exception e) {
144                 LOG.warn("Error closing XML file", e);
145             }
146         }
147
148     }
149
150     /**
151      * Serializes an XML document to a stream.
152      * 
153      * @param aDocument
154      *            Document to serialize.
155      * @param aOs
156      *            Output stream.
157      */
158     public static void serialize(Document aDocument, OutputStream aOs)
159             throws IOException {
160         XMLSerializer serializer = new XMLSerializer(aOs, new OutputFormat());
161         serializer.serialize(aDocument);
162     }
163
164     /**
165      * Serializes an XML document.
166      * 
167      * @param aDocument
168      *            Document to serialize.
169      * @return Serialized document.
170      */
171     public static String serialize(Document aDocument) throws IOException {
172         ByteArrayOutputStream os = new ByteArrayOutputStream();
173         serialize(aDocument, os);
174         return os.toString();
175     }
176
177     /**
178      * Converts a dom4j document into a w3c DOM document.
179      * 
180      * @param aDocument
181      *            Document to convert.
182      * @return W3C DOM document.
183      */
184     public static Document convert(org.dom4j.Document aDocument)
185             throws DocumentException {
186         return new DOMWriter().write(aDocument);
187     }
188
189     /**
190      * Converts a W3C DOM document into a dom4j document.
191      * 
192      * @param aDocument
193      *            Document to convert.
194      * @return Dom4j document.
195      */
196     public static org.dom4j.Document convert(Document aDocument) {
197         return new DOMReader().read(aDocument);
198     }
199
200     /**
201      * Removes duplicate attributes from a DOM tree.This is useful for
202      * postprocessing the output of JTidy as a workaround for a bug in JTidy.
203      * 
204      * @param aNode
205      *            Node to remove duplicate attributes from (recursively).
206      *            Attributes of the node itself are not dealt with. Only the
207      *            child nodes are dealt with.
208      */
209     public static void removeDuplicateAttributes(Node aNode) {
210         NodeList list = aNode.getChildNodes();
211         for (int i = 0; i < list.getLength(); i++) {
212             Node node = list.item(i);
213             if (node instanceof Element) {
214                 removeDuplicateAttributes((Element) node);
215                 removeDuplicateAttributes(node);
216             }
217         }
218     }
219
220     /**
221      * Removes duplicate attributes from an element.
222      * 
223      * @param aElement
224      *            Element.
225      */
226     private static void removeDuplicateAttributes(Element aElement) {
227         NamedNodeMap attributes = aElement.getAttributes();
228         Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
229         List<Attr> attlist = new ArrayList<Attr>();
230         for (int i = 0; i < attributes.getLength(); i++) {
231             Attr attribute = (Attr) attributes.item(i);
232             if (uniqueAttributes.containsKey(attribute.getNodeName())) {
233                 LOG.info("Detected duplicate attribute (will be removed)'"
234                         + attribute.getNodeName() + "'");
235             }
236             uniqueAttributes.put(attribute.getNodeName(), attribute);
237             attlist.add(attribute);
238         }
239         // Remove all attributes from the element.
240         for (Attr att : attlist) {
241             aElement.removeAttributeNode(att);
242         }
243         // Add the unique attributes back to the element.
244         for (Attr att : uniqueAttributes.values()) {
245             aElement.setAttributeNode(att);
246         }
247     }
248 }