1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
|
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.wsf.common;
// $Id: DOMUtils.java 5012 2007-11-08 13:31:55Z heiko.braun@jboss.com $
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.LinkedList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.jboss.logging.Logger;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* DOM2 utilites
*
* @author Thomas.Diesler@jboss.org
*/
public final class DOMUtils
{
private static Logger log = Logger.getLogger(DOMUtils.class);
// All elements created by the same thread are created by the same builder and belong to the same doc
private static ThreadLocal<Document> documentThreadLocal = new ThreadLocal<Document>();
private static ThreadLocal<DocumentBuilder> builderThreadLocal = new ThreadLocal<DocumentBuilder>()
{
protected DocumentBuilder initialValue()
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
setEntityResolver(builder);
return builder;
}
catch (ParserConfigurationException e)
{
throw new RuntimeException("Failed to create DocumentBuilder", e);
}
}
private void setEntityResolver(DocumentBuilder builder)
{
String[] resolvers = new String[] { "org.jboss.ws.core.utils.JBossWSEntityResolver", "org.jboss.util.xml.JBossEntityResolver" };
EntityResolver entityResolver = null;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
for (String resolver : resolvers)
{
try
{
Class<?> resolverClass = loader.loadClass(resolver);
entityResolver = (EntityResolver)resolverClass.newInstance();
}
catch (Exception ex)
{
log.debug("Cannot load: " + resolver);
}
}
if (entityResolver != null)
builder.setEntityResolver(entityResolver);
}
};
public static void clearThreadLocals()
{
documentThreadLocal.remove();
builderThreadLocal.remove();
}
// Hide the constructor
private DOMUtils()
{
}
/** Initialize the DocumentBuilder
*/
public static DocumentBuilder getDocumentBuilder()
{
return builderThreadLocal.get();
}
/** Parse the given XML string and return the root Element
*/
public static Element parse(String xmlString) throws IOException
{
try
{
return parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
}
catch (IOException e)
{
log.error("Cannot parse: " + xmlString);
throw e;
}
}
/** Parse the given XML stream and return the root Element
*/
public static Element parse(InputStream xmlStream) throws IOException
{
try
{
return getDocumentBuilder().parse(xmlStream).getDocumentElement();
}
catch (SAXException se)
{
throw new IOException(se.toString());
}
}
/** Parse the given input source and return the root Element
*/
public static Element parse(InputSource source) throws IOException
{
try
{
return getDocumentBuilder().parse(source).getDocumentElement();
}
catch (SAXException se)
{
throw new IOException(se.toString());
}
}
/** Create an Element for a given name
*/
public static Element createElement(String localPart)
{
Document doc = getOwnerDocument();
log.trace("createElement {}" + localPart);
return doc.createElement(localPart);
}
/** Create an Element for a given name and prefix
*/
public static Element createElement(String localPart, String prefix)
{
Document doc = getOwnerDocument();
log.trace("createElement {}" + prefix + ":" + localPart);
return doc.createElement(prefix + ":" + localPart);
}
/** Create an Element for a given name, prefix and uri
*/
public static Element createElement(String localPart, String prefix, String uri)
{
Document doc = getOwnerDocument();
if (prefix == null || prefix.length() == 0)
{
log.trace("createElement {" + uri + "}" + localPart);
return doc.createElementNS(uri, localPart);
}
else
{
log.trace("createElement {" + uri + "}" + prefix + ":" + localPart);
return doc.createElementNS(uri, prefix + ":" + localPart);
}
}
/** Create an Element for a given QName
*/
public static Element createElement(QName qname)
{
return createElement(qname.getLocalPart(), qname.getPrefix(), qname.getNamespaceURI());
}
/** Create a org.w3c.dom.Text node
*/
public static Text createTextNode(String value)
{
Document doc = getOwnerDocument();
return doc.createTextNode(value);
}
/** Get the qname of the given node.
*/
public static QName getElementQName(Element el)
{
String qualifiedName = el.getNodeName();
return resolveQName(el, qualifiedName);
}
/** Transform the given qualified name into a QName
*/
public static QName resolveQName(Element el, String qualifiedName)
{
QName qname;
String prefix = "";
String namespaceURI = "";
String localPart = qualifiedName;
int colIndex = qualifiedName.indexOf(":");
if (colIndex > 0)
{
prefix = qualifiedName.substring(0, colIndex);
localPart = qualifiedName.substring(colIndex + 1);
if ("xmlns".equals(prefix))
{
namespaceURI = "URI:XML_PREDEFINED_NAMESPACE";
}
else
{
Element nsElement = el;
while (namespaceURI.equals("") && nsElement != null)
{
namespaceURI = nsElement.getAttribute("xmlns:" + prefix);
if (namespaceURI.equals(""))
nsElement = getParentElement(nsElement);
}
}
if (namespaceURI.equals(""))
throw new IllegalArgumentException("Cannot find namespace uri for: " + qualifiedName);
}
else
{
Element nsElement = el;
while (namespaceURI.equals("") && nsElement != null)
{
namespaceURI = nsElement.getAttribute("xmlns");
if (namespaceURI.equals(""))
nsElement = getParentElement(nsElement);
}
}
qname = new QName(namespaceURI, localPart, prefix);
return qname;
}
/** Get the value from the given attribute
*
* @return null if the attribute value is empty or the attribute is not present
*/
public static String getAttributeValue(Element el, String attrName)
{
return getAttributeValue(el, new QName(attrName));
}
/** Get the value from the given attribute
*
* @return null if the attribute value is empty or the attribute is not present
*/
public static String getAttributeValue(Element el, QName attrName)
{
String attr = null;
if ("".equals(attrName.getNamespaceURI()))
attr = el.getAttribute(attrName.getLocalPart());
else attr = el.getAttributeNS(attrName.getNamespaceURI(), attrName.getLocalPart());
if ("".equals(attr))
attr = null;
return attr;
}
/** Get the qname value from the given attribute
*/
public static QName getAttributeValueAsQName(Element el, String attrName)
{
return getAttributeValueAsQName(el, new QName(attrName));
}
/** Get the qname value from the given attribute
*/
public static QName getAttributeValueAsQName(Element el, QName attrName)
{
QName qname = null;
String qualifiedName = getAttributeValue(el, attrName);
if (qualifiedName != null)
{
qname = resolveQName(el, qualifiedName);
}
return qname;
}
/** Get the boolean value from the given attribute
*/
public static boolean getAttributeValueAsBoolean(Element el, String attrName)
{
return getAttributeValueAsBoolean(el, new QName(attrName));
}
/** Get the boolean value from the given attribute
*/
public static boolean getAttributeValueAsBoolean(Element el, QName attrName)
{
String attrVal = getAttributeValue(el, attrName);
boolean ret = "true".equalsIgnoreCase(attrVal) || "1".equalsIgnoreCase(attrVal);
return ret;
}
/** Get the integer value from the given attribute
*/
public static Integer getAttributeValueAsInteger(Element el, String attrName)
{
return getAttributeValueAsInteger(el, new QName(attrName));
}
/** Get the integer value from the given attribute
*/
public static Integer getAttributeValueAsInteger(Element el, QName attrName)
{
String attrVal = getAttributeValue(el, attrName);
return (attrVal != null ? new Integer(attrVal) : null);
}
/** Get the attributes as Map<QName, String>
*/
public static Map getAttributes(Element el)
{
Map attmap = new HashMap();
NamedNodeMap attribs = el.getAttributes();
for (int i = 0; i < attribs.getLength(); i++)
{
Attr attr = (Attr)attribs.item(i);
String name = attr.getName();
QName qname = resolveQName(el, name);
String value = attr.getNodeValue();
attmap.put(qname, value);
}
return attmap;
}
/** Copy attributes between elements
*/
public static void copyAttributes(Element destElement, Element srcElement)
{
NamedNodeMap attribs = srcElement.getAttributes();
for (int i = 0; i < attribs.getLength(); i++)
{
Attr attr = (Attr)attribs.item(i);
String uri = attr.getNamespaceURI();
String qname = attr.getName();
String value = attr.getNodeValue();
// Prevent DOMException: NAMESPACE_ERR: An attempt is made to create or
// change an object in a way which is incorrect with regard to namespaces.
if (uri == null && qname.startsWith("xmlns"))
{
log.trace("Ignore attribute: [uri=" + uri + ",qname=" + qname + ",value=" + value + "]");
}
else
{
destElement.setAttributeNS(uri, qname, value);
}
}
}
/** True if the node has text child elements only
*/
public static boolean hasTextChildNodesOnly(Node node)
{
NodeList nodeList = node.getChildNodes();
if (nodeList.getLength() == 0)
return false;
for (int i = 0; i < nodeList.getLength(); i++)
{
Node acksToChildNode = nodeList.item(i);
if (acksToChildNode.getNodeType() != Node.TEXT_NODE)
return false;
}
return true;
}
/** True if the node has child elements
*/
public static boolean hasChildElements(Node node)
{
NodeList nlist = node.getChildNodes();
for (int i = 0; i < nlist.getLength(); i++)
{
Node child = nlist.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE)
return true;
}
return false;
}
/** Gets child elements
*/
public static Iterator<Element> getChildElements(Node node)
{
List<Element> list = new LinkedList<Element>();
NodeList nlist = node.getChildNodes();
for (int i = 0; i < nlist.getLength(); i++)
{
Node child = nlist.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE)
list.add((Element)child);
}
return list.iterator();
}
/** Get the concatenated text content, or null.
*/
public static String getTextContent(Node node)
{
boolean hasTextContent = false;
StringBuffer buffer = new StringBuffer();
NodeList nlist = node.getChildNodes();
for (int i = 0; i < nlist.getLength(); i++)
{
Node child = nlist.item(i);
if (child.getNodeType() == Node.TEXT_NODE)
{
buffer.append(child.getNodeValue());
hasTextContent = true;
}
}
return (hasTextContent ? buffer.toString() : null);
}
/** Gets the first child element
*/
public static Element getFirstChildElement(Node node)
{
return getFirstChildElementIntern(node, null);
}
/** Gets the first child element for a given local name without namespace
*/
public static Element getFirstChildElement(Node node, String nodeName)
{
return getFirstChildElementIntern(node, new QName(nodeName));
}
/** Gets the first child element for a given qname
*/
public static Element getFirstChildElement(Node node, QName nodeName)
{
return getFirstChildElementIntern(node, nodeName);
}
private static Element getFirstChildElementIntern(Node node, QName nodeName)
{
Element childElement = null;
Iterator it = getChildElementsIntern(node, nodeName);
if (it.hasNext())
{
childElement = (Element)it.next();
}
return childElement;
}
/** Gets the child elements for a given local name without namespace
*/
public static Iterator getChildElements(Node node, String nodeName)
{
return getChildElementsIntern(node, new QName(nodeName));
}
/** Gets the child element for a given qname
*/
public static Iterator getChildElements(Node node, QName nodeName)
{
return getChildElementsIntern(node, nodeName);
}
public static List<Element> getChildElementsAsList(Node node, String nodeName)
{
return getChildElementsAsListIntern(node, new QName(nodeName));
}
public static List<Element> getChildElementsAsList(Node node, QName nodeName)
{
return getChildElementsAsListIntern(node, nodeName);
}
private static List<Element> getChildElementsAsListIntern(Node node, QName nodeName)
{
List<Element> list = new LinkedList<Element>();
NodeList nlist = node.getChildNodes();
for (int i = 0; i < nlist.getLength(); i++)
{
Node child = nlist.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE)
{
if (nodeName == null)
{
list.add((Element)child);
}
else
{
QName qname;
if (nodeName.getNamespaceURI().length() > 0)
{
qname = new QName(child.getNamespaceURI(), child.getLocalName());
}
else
{
qname = new QName(child.getLocalName());
}
if (qname.equals(nodeName))
{
list.add((Element)child);
}
}
}
}
return list;
}
private static Iterator getChildElementsIntern(Node node, QName nodeName)
{
return getChildElementsAsListIntern(node, nodeName).iterator();
}
/** Gets parent element or null if there is none
*/
public static Element getParentElement(Node node)
{
Node parent = node.getParentNode();
return (parent instanceof Element ? (Element)parent : null);
}
/** Get the owner document that is associated with the current thread */
public static Document getOwnerDocument()
{
Document doc = documentThreadLocal.get();
if (doc == null)
{
doc = getDocumentBuilder().newDocument();
documentThreadLocal.set(doc);
}
return doc;
}
public static Element sourceToElement(Source source) throws IOException
{
Element retElement = null;
try
{
if (source instanceof StreamSource)
{
StreamSource streamSource = (StreamSource)source;
InputStream ins = streamSource.getInputStream();
if (ins != null)
{
retElement = DOMUtils.parse(ins);
}
else
{
Reader reader = streamSource.getReader();
retElement = DOMUtils.parse(new InputSource(reader));
}
}
else if (source instanceof DOMSource)
{
DOMSource domSource = (DOMSource)source;
Node node = domSource.getNode();
if (node instanceof Element)
{
retElement = (Element)node;
}
else if (node instanceof Document)
{
retElement = ((Document)node).getDocumentElement();
}
else
{
throw new RuntimeException("Unsupported Node type: " + node.getClass().getName());
}
}
else if (source instanceof SAXSource)
{
// The fact that JAXBSource derives from SAXSource is an implementation detail.
// Thus in general applications are strongly discouraged from accessing methods defined on SAXSource.
// The XMLReader object obtained by the getXMLReader method shall be used only for parsing the InputSource object returned by the getInputSource method.
TransformerFactory tf = TransformerFactory.newInstance();
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.transform(source, new StreamResult(baos));
retElement = DOMUtils.parse(new ByteArrayInputStream(baos.toByteArray()));
}
else
{
throw new RuntimeException("Source type not implemented: " + source.getClass().getName());
}
}
catch (TransformerException ex)
{
IOException ioex = new IOException();
ioex.initCause(ex);
throw ioex;
}
return retElement;
}
}
|