comparison src/main/java/org/dive4elements/artifacts/httpclient/utils/XMLUtils.java @ 71:a857866d162f

Moved directories to org.dive4elements
author Sascha L. Teichmann <teichmann@intevation.de>
date Thu, 25 Apr 2013 11:14:14 +0200
parents src/main/java/de/intevation/artifacts/httpclient/utils/XMLUtils.java@dbf1bfa070af
children 133281653904
comparison
equal deleted inserted replaced
70:da691e917f98 71:a857866d162f
1 /*
2 * Copyright (c) 2010 by Intevation GmbH
3 *
4 * This program is free software under the LGPL (>=v2.1)
5 * Read the file LGPL.txt coming with the software for details
6 * or visit http://www.gnu.org/licenses/ if it does not exist.
7 */
8
9 package de.intevation.artifacts.httpclient.utils;
10
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.io.OutputStream;
14
15 import javax.xml.namespace.NamespaceContext;
16 import javax.xml.namespace.QName;
17 import javax.xml.parsers.DocumentBuilder;
18 import javax.xml.parsers.DocumentBuilderFactory;
19 import javax.xml.parsers.ParserConfigurationException;
20 import javax.xml.transform.Transformer;
21 import javax.xml.transform.TransformerConfigurationException;
22 import javax.xml.transform.TransformerException;
23 import javax.xml.transform.TransformerFactory;
24 import javax.xml.transform.TransformerFactoryConfigurationError;
25 import javax.xml.transform.dom.DOMSource;
26 import javax.xml.transform.stream.StreamResult;
27 import javax.xml.xpath.XPath;
28 import javax.xml.xpath.XPathConstants;
29 import javax.xml.xpath.XPathExpressionException;
30 import javax.xml.xpath.XPathFactory;
31
32 import org.apache.log4j.Logger;
33 import org.w3c.dom.Attr;
34 import org.w3c.dom.Document;
35 import org.w3c.dom.Element;
36 import org.w3c.dom.Node;
37 import org.w3c.dom.NodeList;
38 import org.xml.sax.SAXException;
39
40 /**
41 * This class provides many helper-Methods for handling different kinds of
42 * XML-stuff.
43 * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a>
44 * @author <a href="mailto:sascha.teichmann@intevation.de">Sascha L. Teichmann</a>
45 */
46 public class XMLUtils {
47
48 /**
49 * the logger, used to log exceptions and additonaly information
50 */
51 private static Logger logger = Logger.getLogger(XMLUtils.class);
52
53 /**
54 * Constructor
55 */
56 public XMLUtils() {
57 }
58
59 /**
60 * Class which could be used to create XML-Elements
61 * @author <a href="mailto:sascha.teichmann@intevation.de">Sascha L. Teichmann</a>
62 *
63 */
64 public static class ElementCreator {
65
66 /**
67 * The document the elements should be placed in.
68 */
69 protected Document document;
70
71 /**
72 * The namespace that should be used.
73 */
74 protected String ns;
75
76 /**
77 * The prefix of the namespace that should be used.
78 */
79 protected String prefix;
80
81 /**
82 * Constructor
83 * @param document the document the elements should be placed in
84 * @param ns the namespace that should be used
85 * @param prefix the prefix of the namespace that should be used
86 */
87 public ElementCreator(Document document, String ns, String prefix) {
88 this.document = document;
89 this.ns = ns;
90 this.prefix = prefix;
91 }
92
93 /**
94 * Creates a new element using the given name.
95 * @param name the name of the new element.
96 * @return the new element
97 */
98 public Element create(String name) {
99 Element element = document.createElementNS(ns, name);
100 element.setPrefix(prefix);
101 return element;
102 }
103
104 /**
105 * Adds a new attribute to the given element.
106 * @param element the element where the attribute should be placed in.
107 * @param name the name of the attribute
108 * @param value the value of the attribute
109 */
110 public void addAttr(Element element, String name, String value) {
111 Attr attr = document.createAttributeNS(ns, name);
112 attr.setValue(value);
113 attr.setPrefix(prefix);
114 element.setAttributeNode(attr);
115 }
116 } // class ElementCreator
117
118 /**
119 * Creates a new document.
120 * @return the new document
121 */
122 public static Document newDocument() {
123 try {
124 return DocumentBuilderFactory.newInstance().newDocumentBuilder()
125 .newDocument();
126 } catch (ParserConfigurationException pce) {
127 logger.error(pce.getLocalizedMessage(), pce);
128 }
129 return null;
130 }
131
132 /**
133 * Creates a new <code>XPath</code>-expression
134 * @return the new <code>XPath</code>-expression
135 */
136 public static XPath newXPath() {
137 return newXPath(null);
138 }
139
140 /**
141 * Creates a new <code>XPath</code>-expression
142 * @param namespaceContext the namespacecontext that should be used.
143 * @return the new <code>XPath</code>-expression
144 */
145 public static XPath newXPath(NamespaceContext namespaceContext) {
146 XPathFactory factory = XPathFactory.newInstance();
147 XPath xpath = factory.newXPath();
148 if (namespaceContext != null) {
149 xpath.setNamespaceContext(namespaceContext);
150 }
151 return xpath;
152 }
153
154 /**
155 * Fetch the value of an element or attribute from the given resource
156 * using the query.
157 * @param root the source where the value should be fetch from
158 * @param query the query that should be used to fetch the value
159 * @param namespaceContext the namespacecontext that must match to
160 * fetch the value.
161 * @return the value
162 */
163 public static final String xpathString(Object root, String query,
164 NamespaceContext namespaceContext) {
165 return (String) xpath(root, query, XPathConstants.STRING,
166 namespaceContext);
167 }
168
169 /**
170 * Fetch the object rom the given resource using the query.
171 * @param root the source where the value should be fetch from
172 * @param query the query that should be used to fetch the object
173 * @param returnType the Type that must be used to return the object,
174 * @param namespaceContext the namespacecontext that must match to
175 * fetch the object.
176 * @return the value
177 */
178 public static final Object xpath(Object root, String query,
179 QName returnType,
180 NamespaceContext namespaceContext) {
181 if (root == null) {
182 return null;
183 }
184 try {
185 XPath xpath = XMLUtils.newXPath(namespaceContext);
186 if (xpath != null) {
187 return xpath.evaluate(query, root, returnType);
188 }
189 } catch (XPathExpressionException xpee) {
190 logger.error(xpee.getLocalizedMessage(), xpee);
191 }
192 return null;
193 }
194
195 /**
196 * Fetch the object rom the given resource using the query
197 * and the default <code>ArtifactNamespaceContext</code>
198 * @param root the source where the value should be fetch from
199 * @param query the query that should be used to fetch the object
200 * @param returnType the Type that must be used to return the object
201 * @return the value
202 */
203 public static Object getXPath(Object root, String query, QName returnType) {
204 return getXPath(root,query,returnType,ArtifactNamespaceContext.INSTANCE);
205 }
206
207 /**
208 * Fetch the object rom the given resource using the query
209 * and the default <code>ArtifactNamespaceContext</code>
210 * @param root the source where the value should be fetch from
211 * @param query the query that should be used to fetch the object
212 * @param returnType the Type that must be used to return the object.
213 * @param context the namespacecontext that must match to
214 * fetch the object.
215 * @return the value
216 */
217 public static Object getXPath(
218 Object root, String query, QName returnType, NamespaceContext context
219 ) {
220 return xpath(root, query, returnType, context);
221 }
222
223 /**
224 * Fetch a Nodeset value from a XML-Fragment or XML-Document using the
225 * given query.
226 * @param root the source where the String should be fetched from
227 * @param query the query that should be used,
228 * @return the Nodeset fetched from the source
229 */
230 public static NodeList getNodeSetXPath(Object root, String query) {
231 return (NodeList) getXPath(root, query, XPathConstants.NODESET);
232 }
233
234 /**
235 * Fetch a Node from a XML-Fragment or XML-Document using the
236 * given query.
237 * @param root the source where the Node should be fetched from
238 * @param query the query that should be used,
239 * @return the Node fetched from the source
240 */
241 public static Node getNodeXPath(Object root, String query) {
242 return (Node) getXPath(root, query, XPathConstants.NODE);
243 }
244
245 /**
246 * Fetch a String value from a XML-Fragment or XML-Document using the
247 * given query.
248 * @param root the source where the String should be fetched from
249 * @param xpath the query that should be used,
250 * @return the String fetched from the source
251 */
252 public static String getStringXPath(Object root, String xpath) {
253 return getStringXPath(root, xpath, null);
254 }
255
256 /**
257 * Fetch a String value from a XML-Fragment or XML-Document using the
258 * given query.
259 * @param root the source where the String should be fetched from
260 * @param query the query that should be used,
261 * @param def the default-value that will be returned id no value was found
262 * @return the String fetched from the source
263 */
264 public static String getStringXPath(Object root, String query, String def) {
265 String s = (String) getXPath(root, query, XPathConstants.STRING);
266 return s == null || s.length() == 0 ? def : s;
267 }
268
269 /**
270 * Reads an XML-document from a given <code>InputStream</code>
271 * @param inputStream the <code>InputStream</code> where the document
272 * should be read from
273 * @return the document that could be read.
274 */
275 public static Document readDocument(InputStream inputStream) {
276 Document returnValue = null;
277 try {
278 DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
279 .newInstance();
280 docBuilderFactory.setNamespaceAware(true);
281 DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
282 returnValue = docBuilder.parse(inputStream);
283 } catch (ParserConfigurationException e) {
284 logger.error(e, e);
285 } catch (SAXException e) {
286 logger.error(e, e);
287 } catch (IOException e) {
288 logger.error(e, e);
289 }
290 return returnValue;
291 }
292
293 /**
294 * Writes a given Document to an <code>OutputStream</code>
295 * @param document the document that should be written
296 * @param out the stream where the document should be written to,
297 * @return true if it was successful, false if not.
298 */
299 public static boolean toStream(Document document, OutputStream out) {
300 try {
301 Transformer transformer =
302 TransformerFactory.newInstance().newTransformer();
303 DOMSource source = new DOMSource(document);
304 StreamResult result = new StreamResult(out);
305 transformer.transform(source, result);
306 return true;
307 }
308 catch (TransformerConfigurationException tce) {
309 logger.error(tce.getLocalizedMessage(), tce);
310 }
311 catch (TransformerFactoryConfigurationError tfce) {
312 logger.error(tfce.getLocalizedMessage(), tfce);
313 }
314 catch (TransformerException te) {
315 logger.error(te.getLocalizedMessage(), te);
316 }
317 return false;
318 }
319 }
320 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8:

http://dive4elements.wald.intevation.org