44a9f8ee8268a4cb946d7bc6adb7478e21a84f34
[utils] / support / general / src / main / java / org / wamblee / xml / DomUtils.java
1 /*
2  * Copyright 2005-2010 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 package org.wamblee.xml;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.TreeMap;
27 import java.util.logging.Level;
28 import java.util.logging.Logger;
29
30 import javax.xml.XMLConstants;
31 import javax.xml.parsers.DocumentBuilder;
32 import javax.xml.parsers.DocumentBuilderFactory;
33 import javax.xml.parsers.ParserConfigurationException;
34 import javax.xml.transform.Transformer;
35 import javax.xml.transform.TransformerException;
36 import javax.xml.transform.TransformerFactory;
37 import javax.xml.transform.dom.DOMSource;
38 import javax.xml.transform.stream.StreamResult;
39 import javax.xml.transform.stream.StreamSource;
40 import javax.xml.validation.Schema;
41 import javax.xml.validation.SchemaFactory;
42 import javax.xml.validation.Validator;
43
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.w3c.dom.bootstrap.DOMImplementationRegistry;
51 import org.w3c.dom.ls.DOMImplementationLS;
52 import org.w3c.dom.ls.LSException;
53 import org.w3c.dom.ls.LSInput;
54 import org.w3c.dom.ls.LSParser;
55 import org.xml.sax.SAXException;
56
57 /**
58  * Some basic XML utilities for common reoccuring tasks for DOM documents.
59  * 
60  * @author Erik Brakkee
61  */
62 public final class DomUtils {
63     private static final Logger LOG = Logger
64         .getLogger(DomUtils.class.getName());
65
66     /**
67      * Disabled default constructor.
68      * 
69      */
70     private DomUtils() {
71         // Empty.
72     }
73
74     /**
75      * Parses an XML document from a string.
76      * 
77      * @param aDocument
78      *            document.
79      * 
80      * @return
81      * 
82      */
83     public static Document read(String aDocument) throws XMLException {
84         ByteArrayInputStream is = new ByteArrayInputStream(aDocument.getBytes());
85
86         return read(is);
87     }
88
89     /**
90      * Parses an XML document from a stream.
91      * 
92      * @param aIs
93      *            Input stream.
94      * 
95      * @return
96      * 
97      */
98     public static Document read(InputStream aIs) throws XMLException {
99         try {
100             DOMImplementationRegistry registry = DOMImplementationRegistry
101                 .newInstance();
102
103             DOMImplementationLS impl = (DOMImplementationLS) registry
104                 .getDOMImplementation("LS");
105
106             LSParser builder = impl.createLSParser(
107                 DOMImplementationLS.MODE_SYNCHRONOUS, null);
108             LSInput input = impl.createLSInput();
109             input.setByteStream(aIs);
110             return builder.parse(input);
111         } catch (IllegalAccessException e) {
112             throw new XMLException(e.getMessage(), e);
113         } catch (InstantiationException e) {
114             throw new XMLException(e.getMessage(), e);
115         } catch (ClassNotFoundException e) {
116             throw new XMLException(e.getMessage(), e);
117         } catch (LSException e) {
118             throw new XMLException(e.getMessage(), e);
119         } finally {
120             try {
121                 aIs.close();
122             } catch (Exception e) {
123                 LOG.log(Level.WARNING, "Error closing XML file", e);
124             }
125         }
126     }
127
128     /**
129      * Reads and validates a document against a schema.
130      * 
131      * @param aIs
132      *            Input stream.
133      * @param aSchema
134      *            Schema.
135      * 
136      * @return Parsed and validated document.
137      * 
138      */
139     public static Document readAndValidate(InputStream aIs, InputStream aSchema)
140         throws XMLException {
141         try {
142             Document doc = read(aIs);
143             final Schema schema = SchemaFactory.newInstance(
144                 XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
145                 new StreamSource(aSchema));
146             Validator validator = schema.newValidator();
147             validator.validate(new DOMSource(doc));
148
149             return doc;
150         } catch (SAXException e) {
151             throw new XMLException(e.getMessage(), e);
152         } catch (IOException e) {
153             throw new XMLException(e.getMessage(), e);
154         } finally {
155             try {
156                 aSchema.close();
157             } catch (Exception e) {
158                 LOG.log(Level.WARNING, "Error closing schema", e);
159             }
160
161             try {
162                 aIs.close();
163             } catch (Exception e) {
164                 LOG.log(Level.WARNING, "Error closing XML file", e);
165             }
166         }
167     }
168
169     /**
170      * Serializes an XML document to a stream.
171      * 
172      * @param aDocument
173      *            Document to serialize.
174      * @param aOs
175      *            Output stream.
176      * 
177      */
178     public static void serialize(Document aDocument, OutputStream aOs)
179         throws IOException {
180         try {
181             TransformerFactory factory = TransformerFactory.newInstance();
182             Transformer identityTransform = factory.newTransformer();
183             DOMSource source = new DOMSource(aDocument);
184             StreamResult result = new StreamResult(aOs);
185             identityTransform.transform(source, result);
186         } catch (TransformerException e) {
187             throw new IOException(e.getMessage(), e);
188         }
189     }
190
191     /**
192      * Serializes an XML document.
193      * 
194      * @param aDocument
195      *            Document to serialize.
196      * 
197      * @return Serialized document.
198      * 
199      */
200     public static String serialize(Document aDocument) throws IOException {
201         ByteArrayOutputStream os = new ByteArrayOutputStream();
202         serialize(aDocument, os);
203
204         return os.toString();
205     }
206
207     /**
208      * Removes duplicate attributes from a DOM tree.This is useful for
209      * postprocessing the output of JTidy as a workaround for a bug in JTidy.
210      * 
211      * @param aNode
212      *            Node to remove duplicate attributes from (recursively).
213      *            Attributes of the node itself are not dealt with. Only the
214      *            child nodes are dealt with.
215      */
216     public static void removeDuplicateAttributes(Node aNode) {
217         NodeList list = aNode.getChildNodes();
218
219         for (int i = 0; i < list.getLength(); i++) {
220             Node node = list.item(i);
221
222             if (node instanceof Element) {
223                 removeDuplicateAttributes((Element) node);
224                 removeDuplicateAttributes(node);
225             }
226         }
227     }
228
229     /**
230      * Removes duplicate attributes from an element.
231      * 
232      * @param aElement
233      *            Element.
234      */
235     private static void removeDuplicateAttributes(Element aElement) {
236         NamedNodeMap attributes = aElement.getAttributes();
237         Map<String, Attr> uniqueAttributes = new TreeMap<String, Attr>();
238         List<Attr> attlist = new ArrayList<Attr>();
239
240         for (int i = 0; i < attributes.getLength(); i++) {
241             Attr attribute = (Attr) attributes.item(i);
242
243             if (uniqueAttributes.containsKey(attribute.getNodeName())) {
244                 LOG.info("Detected duplicate attribute (will be removed)'" +
245                     attribute.getNodeName() + "'");
246             }
247
248             uniqueAttributes.put(attribute.getNodeName(), attribute);
249             attlist.add(attribute);
250         }
251
252         // Remove all attributes from the element.
253         for (Attr att : attlist) {
254             aElement.removeAttributeNode(att);
255         }
256
257         // Add the unique attributes back to the element.
258         for (Attr att : uniqueAttributes.values()) {
259             aElement.setAttributeNode(att);
260         }
261     }
262 }