1 16 17 package org.jboss.axis.utils; 18 19 import org.jboss.axis.AxisEngine; 20 import org.jboss.axis.Constants; 21 import org.jboss.axis.InternalException; 22 import org.jboss.axis.MessageContext; 23 import org.jboss.axis.components.encoding.XMLEncoder; 24 import org.jboss.axis.components.encoding.XMLEncoderFactory; 25 import org.jboss.logging.Logger; 26 import org.w3c.dom.Attr ; 27 import org.w3c.dom.CharacterData ; 28 import org.w3c.dom.Document ; 29 import org.w3c.dom.Element ; 30 import org.w3c.dom.NamedNodeMap ; 31 import org.w3c.dom.Node ; 32 import org.w3c.dom.NodeList ; 33 import org.w3c.dom.Text ; 34 import org.xml.sax.ErrorHandler ; 35 import org.xml.sax.InputSource ; 36 import org.xml.sax.SAXException ; 37 import org.xml.sax.SAXParseException ; 38 import org.xml.sax.XMLReader ; 39 40 import javax.xml.namespace.QName ; 41 import javax.xml.parsers.DocumentBuilder ; 42 import javax.xml.parsers.DocumentBuilderFactory ; 43 import javax.xml.parsers.ParserConfigurationException ; 44 import javax.xml.parsers.SAXParser ; 45 import javax.xml.parsers.SAXParserFactory ; 46 import javax.xml.transform.Source ; 47 import javax.xml.transform.dom.DOMSource ; 48 import javax.xml.transform.sax.SAXSource ; 49 import javax.xml.transform.stream.StreamSource ; 50 import java.io.ByteArrayInputStream ; 51 import java.io.ByteArrayOutputStream ; 52 import java.io.IOException ; 53 import java.io.InputStream ; 54 import java.io.OutputStream ; 55 import java.io.OutputStreamWriter ; 56 import java.io.StringWriter ; 57 import java.io.UnsupportedEncodingException ; 58 import java.io.Writer ; 59 import java.net.HttpURLConnection ; 60 import java.net.MalformedURLException ; 61 import java.net.ProtocolException ; 62 import java.net.URL ; 63 import java.net.URLConnection ; 64 import java.util.Iterator ; 65 import java.util.List ; 66 67 68 public class XMLUtils 69 { 70 private static Logger log = Logger.getLogger(XMLUtils.class.getName()); 71 72 public static final String httpAuthCharEncoding = "ISO-8859-1"; 73 private static final String saxParserFactoryProperty = 74 "javax.xml.parsers.SAXParserFactory"; 75 76 private static DocumentBuilderFactory dbf = getDOMFactory(); 77 private static SAXParserFactory saxFactory; 78 79 private static String EMPTY = ""; 80 private static ByteArrayInputStream bais = new ByteArrayInputStream (EMPTY.getBytes()); 81 82 static 83 { 84 initSAXFactory(null, true, false); 86 } 87 88 94 public static String xmlEncodeString(String orig) 95 { 96 XMLEncoder encoder = getXMLEncoder(); 97 return encoder.encode(orig); 98 } 99 100 105 private static XMLEncoder getXMLEncoder() 106 { 107 MessageContext msgContext = MessageContext.getCurrentContext(); 108 XMLEncoder encoder = null; 109 if (msgContext == null) 110 { 111 encoder = XMLEncoderFactory.getDefaultEncoder(); 112 } 113 else 114 { 115 String encoding = (String )msgContext.getAxisEngine().getOption(AxisEngine.PROP_XML_ENCODING); 116 try 117 { 118 if (encoding != null) 119 { 120 encoder = XMLEncoderFactory.getEncoder(encoding); 121 } 122 else 123 { 124 encoder = XMLEncoderFactory.getDefaultEncoder(); 125 } 126 } 127 catch (Exception e) 128 { 129 log.error(Messages.getMessage("exception00"), e); 130 encoder = XMLEncoderFactory.getDefaultEncoder(); 131 } 132 } 133 return encoder; 134 } 135 136 141 public static String getEncoding() 142 { 143 XMLEncoder encoder = getXMLEncoder(); 144 return encoder.getEncoding(); 145 } 146 147 160 public static void initSAXFactory(String factoryClassName, 161 boolean namespaceAware, 162 boolean validating) 163 { 164 if (factoryClassName != null) 165 { 166 try 167 { 168 saxFactory = (SAXParserFactory )Class.forName(factoryClassName).newInstance(); 169 173 if (System.getProperty(saxParserFactoryProperty) == null) 174 { 175 System.setProperty(saxParserFactoryProperty, factoryClassName); 176 } 177 } 178 catch (Exception e) 179 { 180 log.error(Messages.getMessage("exception00"), e); 181 saxFactory = null; 182 } 183 } 184 else 185 { 186 saxFactory = SAXParserFactory.newInstance(); 187 } 188 saxFactory.setNamespaceAware(namespaceAware); 189 saxFactory.setValidating(validating); 190 } 191 192 private static DocumentBuilderFactory getDOMFactory() 193 { 194 DocumentBuilderFactory dbf; 195 try 196 { 197 dbf = DocumentBuilderFactory.newInstance(); 198 dbf.setNamespaceAware(true); 199 } 200 catch (Exception e) 201 { 202 log.error(Messages.getMessage("exception00"), e); 203 dbf = null; 204 } 205 return (dbf); 206 } 207 208 213 public static synchronized SAXParser getSAXParser() 214 { 215 try 216 { 217 SAXParser parser = saxFactory.newSAXParser(); 218 XMLReader reader = parser.getXMLReader(); 219 reader.setEntityResolver(new DefaultEntityResolver()); 225 reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); 226 return parser; 227 } 228 catch (ParserConfigurationException e) 229 { 230 log.error(Messages.getMessage("parserConfigurationException00"), e); 231 return null; 232 } 233 catch (SAXException se) 234 { 235 log.error(Messages.getMessage("SAXException00"), se); 236 return null; 237 } 238 } 239 240 241 247 public static Document newDocument() 248 throws ParserConfigurationException 249 { 250 synchronized (dbf) 251 { 252 return dbf.newDocumentBuilder().newDocument(); 253 } 254 } 255 256 264 public static Document newDocument(InputSource inp) 265 throws ParserConfigurationException , SAXException , IOException 266 { 267 DocumentBuilder db; 268 synchronized (dbf) 269 { 270 db = dbf.newDocumentBuilder(); 271 } 272 db.setEntityResolver(new DefaultEntityResolver()); 273 db.setErrorHandler(new ParserErrorHandler()); 274 return (db.parse(inp)); 275 } 276 277 285 public static Document newDocument(InputStream inp) 286 throws ParserConfigurationException , SAXException , IOException 287 { 288 return XMLUtils.newDocument(new InputSource (inp)); 289 } 290 291 299 public static Document newDocument(String uri) 300 throws ParserConfigurationException , SAXException , IOException 301 { 302 return XMLUtils.newDocument(uri, null, null); 305 } 306 307 318 public static Document newDocument(String uri, String username, String password) 319 throws ParserConfigurationException , SAXException , IOException 320 { 321 InputSource ins = XMLUtils.getInputSourceFromURI(uri, username, password); 322 Document doc = XMLUtils.newDocument(ins); 323 if (ins.getByteStream() != null) 325 { 326 ins.getByteStream().close(); 327 } 328 else if (ins.getCharacterStream() != null) 329 { 330 ins.getCharacterStream().close(); 331 } 332 return doc; 333 } 334 335 public static String ElementToString(Node element, boolean omitXMLDecl) 336 { 337 return DOM2Writer.nodeToString(element, omitXMLDecl); 338 } 339 340 346 public static String ElementToString(Node element) 347 { 348 return ElementToString(element, true); 349 } 350 351 357 public static String DocumentToString(Document doc) 358 { 359 return ElementToString(doc.getDocumentElement(), false); 360 } 361 362 public static String PrettyDocumentToString(Document doc) 363 { 364 StringWriter sw = new StringWriter (); 365 PrettyElementToWriter(doc.getDocumentElement(), sw); 366 return sw.toString(); 367 } 368 369 public static void ElementToWriter(Element element, Writer writer, 370 boolean omitXMLDecl, 371 boolean pretty) 372 { 373 DOM2Writer.serializeAsXML(element, writer, omitXMLDecl, pretty, 0); 374 } 375 376 public static void ElementToStream(Element element, OutputStream out) 377 { 378 Writer writer = getWriter(out); 379 ElementToWriter(element, writer, true, false); 380 } 381 382 public static void PrettyElementToStream(Element element, OutputStream out) 383 { 384 Writer writer = getWriter(out); 385 ElementToWriter(element, writer, true, true); 386 } 387 388 public static void ElementToWriter(Element element, Writer writer) 389 { 390 ElementToWriter(element, writer, true, false); 391 } 392 393 public static void PrettyElementToWriter(Element element, Writer writer) 394 { 395 ElementToWriter(element, writer, true, true); 396 } 397 398 public static void DocumentToStream(Document doc, OutputStream out) 399 { 400 Writer writer = getWriter(out); 401 ElementToWriter(doc.getDocumentElement(), writer, false, false); 402 } 403 404 public static void PrettyDocumentToStream(Document doc, OutputStream out) 405 { 406 Writer writer = getWriter(out); 407 ElementToWriter(doc.getDocumentElement(), writer, false, true); 408 } 409 410 private static Writer getWriter(OutputStream os) 411 { 412 Writer writer = null; 413 try 414 { 415 writer = new OutputStreamWriter (os, "UTF-8"); 416 } 417 catch (UnsupportedEncodingException uee) 418 { 419 log.error(Messages.getMessage("exception00"), uee); 420 writer = new OutputStreamWriter (os); 421 } 422 return writer; 423 } 424 425 public static void DocumentToWriter(Document doc, Writer writer) 426 { 427 ElementToWriter(doc.getDocumentElement(), writer, false, false); 428 } 429 430 public static void PrettyDocumentToWriter(Document doc, Writer writer) 431 { 432 ElementToWriter(doc.getDocumentElement(), writer, false, true); 433 } 434 435 443 public static Element StringToElement(String namespace, String name, String string) 444 { 445 try 446 { 447 Document doc = XMLUtils.newDocument(); 448 Element element = doc.createElementNS(namespace, name); 449 Text text = doc.createTextNode(string); 450 element.appendChild(text); 451 return element; 452 } 453 catch (ParserConfigurationException e) 454 { 455 throw new InternalException(e); 457 } 458 } 459 460 468 public static String getInnerXMLString(Element element) 469 { 470 String elementString = ElementToString(element); 471 int start, end; 472 start = elementString.indexOf(">") + 1; 473 end = elementString.lastIndexOf("</"); 474 if (end > 0) 475 return elementString.substring(start, end); 476 else 477 return null; 478 } 479 480 public static String getPrefix(String uri, Node e) 481 { 482 while (e != null && (e.getNodeType() == Element.ELEMENT_NODE)) 483 { 484 NamedNodeMap attrs = e.getAttributes(); 485 for (int n = 0; n < attrs.getLength(); n++) 486 { 487 Attr a = (Attr )attrs.item(n); 488 String name; 489 if ((name = a.getName()).startsWith("xmlns:") && 490 a.getNodeValue().equals(uri)) 491 { 492 return name.substring(6); 493 } 494 } 495 e = e.getParentNode(); 496 } 497 return null; 498 } 499 500 512 public static String getNamespace(String prefix, Node e, Node stopNode) 513 { 514 while (e != null && (e.getNodeType() == Node.ELEMENT_NODE)) 515 { 516 Attr attr = null; 517 if (prefix == null) 518 { 519 attr = ((Element )e).getAttributeNode("xmlns"); 520 } 521 else 522 { 523 attr = ((Element )e).getAttributeNodeNS(Constants.NS_URI_XMLNS, 524 prefix); 525 } 526 if (attr != null) return attr.getValue(); 527 if (e == stopNode) 528 return null; 529 e = e.getParentNode(); 530 } 531 return null; 532 } 533 534 public static String getNamespace(String prefix, Node e) 535 { 536 return getNamespace(prefix, e, null); 537 } 538 539 545 public static QName getQNameFromString(String str, Node e) 546 { 547 return getQNameFromString(str, e, false); 548 } 549 550 557 public static QName getFullQNameFromString(String str, Node e) 558 { 559 return getQNameFromString(str, e, true); 560 } 561 562 private static QName getQNameFromString(String str, Node e, boolean defaultNS) 563 { 564 if (str == null || e == null) 565 return null; 566 567 int idx = str.indexOf(':'); 568 if (idx > -1) 569 { 570 String prefix = str.substring(0, idx); 571 String ns = getNamespace(prefix, e); 572 if (ns == null) 573 { 574 log.warn("Cannot obtain namespaceURI for prefix: " + prefix); 575 return null; 576 } 577 return new QName (ns, str.substring(idx + 1)); 578 } 579 else 580 { 581 if (defaultNS) 582 { 583 String ns = getNamespace(null, e); 584 if (ns != null) 585 return new QName (ns, str); 586 } 587 return new QName ("", str); 588 } 589 } 590 591 595 public static String getStringForQName(QName qname, Element e) 596 { 597 String uri = qname.getNamespaceURI(); 598 String prefix = getPrefix(uri, e); 599 if (prefix == null) 600 { 601 int i = 1; 602 prefix = "ns" + i; 603 while (getNamespace(prefix, e) != null) 604 { 605 i++; 606 prefix = "ns" + i; 607 } 608 e.setAttributeNS(Constants.NS_URI_XMLNS, 609 "xmlns:" + prefix, uri); 610 } 611 return prefix + ":" + qname.getLocalPart(); 612 } 613 614 623 public static String getChildCharacterData(Element parentEl) 624 { 625 if (parentEl == null) 626 { 627 return null; 628 } 629 Node tempNode = parentEl.getFirstChild(); 630 StringBuffer strBuf = new StringBuffer (); 631 CharacterData charData; 632 633 while (tempNode != null) 634 { 635 switch (tempNode.getNodeType()) 636 { 637 case Node.TEXT_NODE: 638 case Node.CDATA_SECTION_NODE: 639 charData = (CharacterData )tempNode; 640 strBuf.append(charData.getData()); 641 break; 642 } 643 tempNode = tempNode.getNextSibling(); 644 } 645 return strBuf.toString(); 646 } 647 648 public static class ParserErrorHandler implements ErrorHandler 649 { 650 private static Logger log = Logger.getLogger(ParserErrorHandler.class.getName()); 651 652 655 private String getParseExceptionInfo(SAXParseException spe) 656 { 657 String systemId = spe.getSystemId(); 658 if (systemId == null) 659 { 660 systemId = "null"; 661 } 662 String info = "URI=" + systemId + 663 " Line=" + spe.getLineNumber() + 664 ": " + spe.getMessage(); 665 return info; 666 } 667 668 671 public void warning(SAXParseException spe) throws SAXException 672 { 673 if (log.isDebugEnabled()) 674 log.debug(Messages.getMessage("warning00", getParseExceptionInfo(spe))); 675 } 676 677 public void error(SAXParseException spe) throws SAXException 678 { 679 String message = "Error: " + getParseExceptionInfo(spe); 680 throw new SAXException (message); 681 } 682 683 public void fatalError(SAXParseException spe) throws SAXException 684 { 685 String message = "Fatal Error: " + getParseExceptionInfo(spe); 686 throw new SAXException (message); 687 } 688 } 689 690 691 699 public static InputSource getInputSourceFromURI(String uri) 700 { 701 return new InputSource (uri); 702 } 703 704 709 public static InputSource sourceToInputSource(Source source) 710 { 711 if (source instanceof SAXSource ) 712 { 713 return ((SAXSource )source).getInputSource(); 714 } 715 else if (source instanceof DOMSource ) 716 { 717 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 718 Node node = ((DOMSource )source).getNode(); 719 if (node instanceof Document ) 720 { 721 node = ((Document )node).getDocumentElement(); 722 } 723 Element domElement = (Element )node; 724 ElementToStream(domElement, baos); 725 InputSource isource = new InputSource (source.getSystemId()); 726 isource.setByteStream(new ByteArrayInputStream (baos.toByteArray())); 727 return isource; 728 } 729 else if (source instanceof StreamSource ) 730 { 731 StreamSource ss = (StreamSource )source; 732 InputSource isource = new InputSource (ss.getSystemId()); 733 isource.setByteStream(ss.getInputStream()); 734 isource.setCharacterStream(ss.getReader()); 735 isource.setPublicId(ss.getPublicId()); 736 return isource; 737 } 738 else 739 { 740 return getInputSourceFromURI(source.getSystemId()); 741 } 742 } 743 744 758 private static InputSource getInputSourceFromURI(String uri, 759 String username, 760 String password) 761 throws IOException , ProtocolException , UnsupportedEncodingException 762 { 763 URL wsdlurl = null; 764 try 765 { 766 wsdlurl = new URL (uri); 767 } 768 catch (MalformedURLException e) 769 { 770 return new InputSource (uri); 773 } 774 775 if (username == null && wsdlurl.getUserInfo() == null) 777 { 778 return new InputSource (uri); 779 } 780 781 if (!wsdlurl.getProtocol().startsWith("http")) 783 { 784 return new InputSource (uri); 785 } 786 787 URLConnection connection = wsdlurl.openConnection(); 788 if (!(connection instanceof HttpURLConnection )) 790 { 791 return new InputSource (uri); 793 } 794 HttpURLConnection uconn = (HttpURLConnection )connection; 795 String userinfo = wsdlurl.getUserInfo(); 796 uconn.setRequestMethod("GET"); 797 uconn.setAllowUserInteraction(false); 798 uconn.setDefaultUseCaches(false); 799 uconn.setDoInput(true); 800 uconn.setDoOutput(false); 801 uconn.setInstanceFollowRedirects(true); 802 uconn.setUseCaches(false); 803 804 String auth = null; 806 if (userinfo != null) 807 { 808 auth = userinfo; 809 } 810 else if (username != null) 811 { 812 auth = (password == null) ? username : username + ":" + password; 813 } 814 815 if (auth != null) 816 { 817 uconn.setRequestProperty("Authorization", 818 "Basic " + 819 base64encode(auth.getBytes(httpAuthCharEncoding))); 820 } 821 822 uconn.connect(); 823 824 return new InputSource (uconn.getInputStream()); 825 } 826 827 public static final String base64encode(byte[] bytes) 828 { 829 return new String (Base64.encode(bytes)); 830 } 831 832 public static InputSource getEmptyInputSource() 833 { 834 return new InputSource (bais); 835 } 836 837 844 public static Node findNode(Node node, QName name) 845 { 846 if (name.getNamespaceURI().equals(node.getNamespaceURI()) && 847 name.getLocalPart().equals(node.getLocalName())) 848 return node; 849 NodeList children = node.getChildNodes(); 850 for (int i = 0; i < children.getLength(); i++) 851 { 852 Node ret = findNode(children.item(i), name); 853 if (ret != null) 854 return ret; 855 } 856 return null; 857 } 858 859 864 public static void normalize(Node node) 865 { 866 if (node.getNodeType() == Node.TEXT_NODE) 867 { 868 String data = ((Text )node).getData(); 869 if (data.length() > 0) 870 { 871 char ch = data.charAt(data.length() - 1); 872 if (ch == '\n' || ch == '\r' || ch == ' ') 873 { 874 String data2 = trim(data); 875 ((Text )node).setData(data2); 876 } 877 } 878 } 879 for (Node currentChild = node.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) 880 { 881 normalize(currentChild); 882 } 883 } 884 885 public static String trim(String str) 886 { 887 if (str.length() == 0) 888 { 889 return str; 890 } 891 892 if (str.length() == 1) 893 { 894 if ("\r".equals(str) || "\n".equals(str)) 895 { 896 return ""; 897 } 898 else 899 { 900 return str; 901 } 902 } 903 904 int lastIdx = str.length() - 1; 905 char last = str.charAt(lastIdx); 906 while (lastIdx > 0) 907 { 908 if (last != '\n' && last != '\r' && last != ' ') 909 break; 910 lastIdx--; 911 last = str.charAt(lastIdx); 912 } 913 if (lastIdx == 0) 914 return ""; 915 return str.substring(0, lastIdx); 916 } 917 918 925 public static Element [] asElementArray(List list) 926 { 927 928 Element [] elements = new Element [list.size()]; 929 930 int i = 0; 931 Iterator detailIter = list.iterator(); 932 while (detailIter.hasNext()) 933 { 934 elements[i++] = (Element )detailIter.next(); 935 } 936 937 return elements; 938 } 939 } 940 | Popular Tags |