KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > axis > utils > XMLUtils


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
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.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 JavaDoc;
27 import org.w3c.dom.CharacterData JavaDoc;
28 import org.w3c.dom.Document JavaDoc;
29 import org.w3c.dom.Element JavaDoc;
30 import org.w3c.dom.NamedNodeMap JavaDoc;
31 import org.w3c.dom.Node JavaDoc;
32 import org.w3c.dom.NodeList JavaDoc;
33 import org.w3c.dom.Text JavaDoc;
34 import org.xml.sax.ErrorHandler JavaDoc;
35 import org.xml.sax.InputSource JavaDoc;
36 import org.xml.sax.SAXException JavaDoc;
37 import org.xml.sax.SAXParseException JavaDoc;
38 import org.xml.sax.XMLReader JavaDoc;
39
40 import javax.xml.namespace.QName JavaDoc;
41 import javax.xml.parsers.DocumentBuilder JavaDoc;
42 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
43 import javax.xml.parsers.ParserConfigurationException JavaDoc;
44 import javax.xml.parsers.SAXParser JavaDoc;
45 import javax.xml.parsers.SAXParserFactory JavaDoc;
46 import javax.xml.transform.Source JavaDoc;
47 import javax.xml.transform.dom.DOMSource JavaDoc;
48 import javax.xml.transform.sax.SAXSource JavaDoc;
49 import javax.xml.transform.stream.StreamSource JavaDoc;
50 import java.io.ByteArrayInputStream JavaDoc;
51 import java.io.ByteArrayOutputStream JavaDoc;
52 import java.io.IOException JavaDoc;
53 import java.io.InputStream JavaDoc;
54 import java.io.OutputStream JavaDoc;
55 import java.io.OutputStreamWriter JavaDoc;
56 import java.io.StringWriter JavaDoc;
57 import java.io.UnsupportedEncodingException JavaDoc;
58 import java.io.Writer JavaDoc;
59 import java.net.HttpURLConnection JavaDoc;
60 import java.net.MalformedURLException JavaDoc;
61 import java.net.ProtocolException JavaDoc;
62 import java.net.URL JavaDoc;
63 import java.net.URLConnection JavaDoc;
64 import java.util.Iterator JavaDoc;
65 import java.util.List JavaDoc;
66
67
68 public class XMLUtils
69 {
70    private static Logger log = Logger.getLogger(XMLUtils.class.getName());
71
72    public static final String JavaDoc httpAuthCharEncoding = "ISO-8859-1";
73    private static final String JavaDoc saxParserFactoryProperty =
74            "javax.xml.parsers.SAXParserFactory";
75
76    private static DocumentBuilderFactory JavaDoc dbf = getDOMFactory();
77    private static SAXParserFactory JavaDoc saxFactory;
78
79    private static String JavaDoc EMPTY = "";
80    private static ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(EMPTY.getBytes());
81
82    static
83    {
84       // Initialize SAX Parser factory defaults
85
initSAXFactory(null, true, false);
86    }
87
88    /**
89     * Encode a string appropriately for XML.
90     *
91     * @param orig the String to encode
92     * @return a String in which XML special chars are repalced by entities
93     */

94    public static String JavaDoc xmlEncodeString(String JavaDoc orig)
95    {
96       XMLEncoder encoder = getXMLEncoder();
97       return encoder.encode(orig);
98    }
99
100    /**
101     * Get the current XMLEncoder
102     *
103     * @return XMLEncoder
104     */

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 JavaDoc encoding = (String JavaDoc)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 JavaDoc e)
128          {
129             log.error(Messages.getMessage("exception00"), e);
130             encoder = XMLEncoderFactory.getDefaultEncoder();
131          }
132       }
133       return encoder;
134    }
135
136    /**
137     * Get the current encoding in effect
138     *
139     * @return string
140     */

141    public static String JavaDoc getEncoding()
142    {
143       XMLEncoder encoder = getXMLEncoder();
144       return encoder.getEncoding();
145    }
146
147    /**
148     * Initialize the SAX parser factory.
149     *
150     * @param factoryClassName The (optional) class name of the desired
151     * SAXParserFactory implementation. Will be
152     * assigned to the system property
153     * <b>javax.xml.parsers.SAXParserFactory</b>
154     * unless this property is already set.
155     * If <code>null</code>, leaves current setting
156     * alone.
157     * @param namespaceAware true if we want a namespace-aware parser
158     * @param validating true if we want a validating parser
159     */

160    public static void initSAXFactory(String JavaDoc factoryClassName,
161                                      boolean namespaceAware,
162                                      boolean validating)
163    {
164       if (factoryClassName != null)
165       {
166          try
167          {
168             saxFactory = (SAXParserFactory JavaDoc)Class.forName(factoryClassName).newInstance();
169             /*
170              * Set the system property only if it is not already set to
171              * avoid corrupting environments in which Axis is embedded.
172              */

173             if (System.getProperty(saxParserFactoryProperty) == null)
174             {
175                System.setProperty(saxParserFactoryProperty, factoryClassName);
176             }
177          }
178          catch (Exception JavaDoc 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 JavaDoc getDOMFactory()
193    {
194       DocumentBuilderFactory JavaDoc dbf;
195       try
196       {
197          dbf = DocumentBuilderFactory.newInstance();
198          dbf.setNamespaceAware(true);
199       }
200       catch (Exception JavaDoc e)
201       {
202          log.error(Messages.getMessage("exception00"), e);
203          dbf = null;
204       }
205       return (dbf);
206    }
207
208    /**
209     * Get a SAX parser instance from the JAXP factory.
210     *
211     * @return a SAXParser instance.
212     */

213    public static synchronized SAXParser JavaDoc getSAXParser()
214    {
215       try
216       {
217          SAXParser JavaDoc parser = saxFactory.newSAXParser();
218          XMLReader JavaDoc reader = parser.getXMLReader();
219          // parser.getParser().setEntityResolver(new DefaultEntityResolver());
220
// The above commented line and the following line are added
221
// for preventing XXE (bug #14105).
222
// We may need to uncomment the deprecated setting
223
// in case that it is considered necessary.
224
reader.setEntityResolver(new DefaultEntityResolver());
225          reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
226          return parser;
227       }
228       catch (ParserConfigurationException JavaDoc e)
229       {
230          log.error(Messages.getMessage("parserConfigurationException00"), e);
231          return null;
232       }
233       catch (SAXException JavaDoc se)
234       {
235          log.error(Messages.getMessage("SAXException00"), se);
236          return null;
237       }
238    }
239
240
241    /**
242     * Get an empty new Document
243     *
244     * @return Document
245     * @throws ParserConfigurationException if construction problems occur
246     */

247    public static Document JavaDoc newDocument()
248            throws ParserConfigurationException JavaDoc
249    {
250       synchronized (dbf)
251       {
252          return dbf.newDocumentBuilder().newDocument();
253       }
254    }
255
256    /**
257     * Get a new Document read from the input source
258     *
259     * @return Document
260     * @throws ParserConfigurationException if construction problems occur
261     * @throws SAXException if the document has xml sax problems
262     * @throws IOException if i/o exceptions occur
263     */

264    public static Document JavaDoc newDocument(InputSource JavaDoc inp)
265            throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc
266    {
267       DocumentBuilder JavaDoc 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    /**
278     * Get a new Document read from the input stream
279     *
280     * @return Document
281     * @throws ParserConfigurationException if construction problems occur
282     * @throws SAXException if the document has xml sax problems
283     * @throws IOException if i/o exceptions occur
284     */

285    public static Document JavaDoc newDocument(InputStream JavaDoc inp)
286            throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc
287    {
288       return XMLUtils.newDocument(new InputSource JavaDoc(inp));
289    }
290
291    /**
292     * Get a new Document read from the indicated uri
293     *
294     * @return Document
295     * @throws ParserConfigurationException if construction problems occur
296     * @throws SAXException if the document has xml sax problems
297     * @throws IOException if i/o exceptions occur
298     */

299    public static Document JavaDoc newDocument(String JavaDoc uri)
300            throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc
301    {
302       // call the authenticated version as there might be
303
// username/password info embeded in the uri.
304
return XMLUtils.newDocument(uri, null, null);
305    }
306
307    /**
308     * Create a new document from the given URI, use the username and password
309     * if the URI requires authentication.
310     *
311     * @param uri the resource to get
312     * @param username basic auth username
313     * @param password basic auth password
314     * @throws ParserConfigurationException if construction problems occur
315     * @throws SAXException if the document has xml sax problems
316     * @throws IOException if i/o exceptions occur
317     */

318    public static Document JavaDoc newDocument(String JavaDoc uri, String JavaDoc username, String JavaDoc password)
319            throws ParserConfigurationException JavaDoc, SAXException JavaDoc, IOException JavaDoc
320    {
321       InputSource JavaDoc ins = XMLUtils.getInputSourceFromURI(uri, username, password);
322       Document JavaDoc doc = XMLUtils.newDocument(ins);
323       // Close the Stream
324
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 JavaDoc ElementToString(Node JavaDoc element, boolean omitXMLDecl)
336    {
337       return DOM2Writer.nodeToString(element, omitXMLDecl);
338    }
339
340    /**
341     * turn an element into an XML fragment
342     *
343     * @param element
344     * @return stringified element
345     */

346    public static String JavaDoc ElementToString(Node JavaDoc element)
347    {
348       return ElementToString(element, true);
349    }
350
351    /**
352     * Turn a whole DOM document into XML
353     *
354     * @param doc DOM document
355     * @return string representation of the document, including XML declaration
356     */

357    public static String JavaDoc DocumentToString(Document JavaDoc doc)
358    {
359       return ElementToString(doc.getDocumentElement(), false);
360    }
361
362    public static String JavaDoc PrettyDocumentToString(Document JavaDoc doc)
363    {
364       StringWriter JavaDoc sw = new StringWriter JavaDoc();
365       PrettyElementToWriter(doc.getDocumentElement(), sw);
366       return sw.toString();
367    }
368
369    public static void ElementToWriter(Element JavaDoc element, Writer JavaDoc writer,
370                                       boolean omitXMLDecl,
371                                       boolean pretty)
372    {
373       DOM2Writer.serializeAsXML(element, writer, omitXMLDecl, pretty, 0);
374    }
375
376    public static void ElementToStream(Element JavaDoc element, OutputStream JavaDoc out)
377    {
378       Writer JavaDoc writer = getWriter(out);
379       ElementToWriter(element, writer, true, false);
380    }
381
382    public static void PrettyElementToStream(Element JavaDoc element, OutputStream JavaDoc out)
383    {
384       Writer JavaDoc writer = getWriter(out);
385       ElementToWriter(element, writer, true, true);
386    }
387
388    public static void ElementToWriter(Element JavaDoc element, Writer JavaDoc writer)
389    {
390       ElementToWriter(element, writer, true, false);
391    }
392
393    public static void PrettyElementToWriter(Element JavaDoc element, Writer JavaDoc writer)
394    {
395       ElementToWriter(element, writer, true, true);
396    }
397
398    public static void DocumentToStream(Document JavaDoc doc, OutputStream JavaDoc out)
399    {
400       Writer JavaDoc writer = getWriter(out);
401       ElementToWriter(doc.getDocumentElement(), writer, false, false);
402    }
403
404    public static void PrettyDocumentToStream(Document JavaDoc doc, OutputStream JavaDoc out)
405    {
406       Writer JavaDoc writer = getWriter(out);
407       ElementToWriter(doc.getDocumentElement(), writer, false, true);
408    }
409
410    private static Writer JavaDoc getWriter(OutputStream JavaDoc os)
411    {
412       Writer JavaDoc writer = null;
413       try
414       {
415          writer = new OutputStreamWriter JavaDoc(os, "UTF-8");
416       }
417       catch (UnsupportedEncodingException JavaDoc uee)
418       {
419          log.error(Messages.getMessage("exception00"), uee);
420          writer = new OutputStreamWriter JavaDoc(os);
421       }
422       return writer;
423    }
424
425    public static void DocumentToWriter(Document JavaDoc doc, Writer JavaDoc writer)
426    {
427       ElementToWriter(doc.getDocumentElement(), writer, false, false);
428    }
429
430    public static void PrettyDocumentToWriter(Document JavaDoc doc, Writer JavaDoc writer)
431    {
432       ElementToWriter(doc.getDocumentElement(), writer, false, true);
433    }
434
435    /**
436     * Convert a simple string to an element with a text node
437     *
438     * @param namespace - element namespace
439     * @param name - element name
440     * @param string - value of the text node
441     * @return element - an XML Element, null if no element was created
442     */

443    public static Element JavaDoc StringToElement(String JavaDoc namespace, String JavaDoc name, String JavaDoc string)
444    {
445       try
446       {
447          Document JavaDoc doc = XMLUtils.newDocument();
448          Element JavaDoc element = doc.createElementNS(namespace, name);
449          Text JavaDoc text = doc.createTextNode(string);
450          element.appendChild(text);
451          return element;
452       }
453       catch (ParserConfigurationException JavaDoc e)
454       {
455          // This should not occur
456
throw new InternalException(e);
457       }
458    }
459
460    /**
461     * get the inner XML inside an element as a string. This is done by
462     * converting the XML to its string representation, then extracting the
463     * subset between beginning and end tags.
464     *
465     * @param element
466     * @return textual body of the element, or null for no inner body
467     */

468    public static String JavaDoc getInnerXMLString(Element JavaDoc element)
469    {
470       String JavaDoc 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 JavaDoc getPrefix(String JavaDoc uri, Node JavaDoc e)
481    {
482       while (e != null && (e.getNodeType() == Element.ELEMENT_NODE))
483       {
484          NamedNodeMap JavaDoc attrs = e.getAttributes();
485          for (int n = 0; n < attrs.getLength(); n++)
486          {
487             Attr JavaDoc a = (Attr JavaDoc)attrs.item(n);
488             String JavaDoc 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    /**
501     * Searches for the namespace URI of the given prefix in the given DOM range.
502     * <p/>
503     * The namespace is not searched in parent of the "stopNode". This is
504     * usefull to get all the needed namespaces when you need to ouput only a
505     * subtree of a DOM document.
506     *
507     * @param prefix the prefix to find
508     * @param e the starting node
509     * @param stopNode null to search in all the document or a parent node where the search must stop.
510     * @return null if no namespace is found, or the namespace URI.
511     */

512    public static String JavaDoc getNamespace(String JavaDoc prefix, Node JavaDoc e, Node JavaDoc stopNode)
513    {
514       while (e != null && (e.getNodeType() == Node.ELEMENT_NODE))
515       {
516          Attr JavaDoc attr = null;
517          if (prefix == null)
518          {
519             attr = ((Element JavaDoc)e).getAttributeNode("xmlns");
520          }
521          else
522          {
523             attr = ((Element JavaDoc)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 JavaDoc getNamespace(String JavaDoc prefix, Node JavaDoc e)
535    {
536       return getNamespace(prefix, e, null);
537    }
538
539    /**
540     * Return a QName when passed a string like "foo:bar" by mapping
541     * the "foo" prefix to a namespace in the context of the given Node.
542     *
543     * @return a QName generated from the given string representation
544     */

545    public static QName JavaDoc getQNameFromString(String JavaDoc str, Node JavaDoc e)
546    {
547       return getQNameFromString(str, e, false);
548    }
549
550    /**
551     * Return a QName when passed a string like "foo:bar" by mapping
552     * the "foo" prefix to a namespace in the context of the given Node.
553     * If default namespace is found it is returned as part of the QName.
554     *
555     * @return a QName generated from the given string representation
556     */

557    public static QName JavaDoc getFullQNameFromString(String JavaDoc str, Node JavaDoc e)
558    {
559       return getQNameFromString(str, e, true);
560    }
561
562    private static QName JavaDoc getQNameFromString(String JavaDoc str, Node JavaDoc 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 JavaDoc prefix = str.substring(0, idx);
571          String JavaDoc 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 JavaDoc(ns, str.substring(idx + 1));
578       }
579       else
580       {
581          if (defaultNS)
582          {
583             String JavaDoc ns = getNamespace(null, e);
584             if (ns != null)
585                return new QName JavaDoc(ns, str);
586          }
587          return new QName JavaDoc("", str);
588       }
589    }
590
591    /**
592     * Return a string for a particular QName, mapping a new prefix
593     * if necessary.
594     */

595    public static String JavaDoc getStringForQName(QName JavaDoc qname, Element JavaDoc e)
596    {
597       String JavaDoc uri = qname.getNamespaceURI();
598       String JavaDoc 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    /**
615     * Concat all the text and cdata node children of this elem and return
616     * the resulting text.
617     * (by Matt Duftler)
618     *
619     * @param parentEl the element whose cdata/text node values are to
620     * be combined.
621     * @return the concatanated string.
622     */

623    public static String JavaDoc getChildCharacterData(Element JavaDoc parentEl)
624    {
625       if (parentEl == null)
626       {
627          return null;
628       }
629       Node JavaDoc tempNode = parentEl.getFirstChild();
630       StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
631       CharacterData JavaDoc 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 JavaDoc)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 JavaDoc
649    {
650       private static Logger log = Logger.getLogger(ParserErrorHandler.class.getName());
651
652       /**
653        * Returns a string describing parse exception details
654        */

655       private String JavaDoc getParseExceptionInfo(SAXParseException JavaDoc spe)
656       {
657          String JavaDoc systemId = spe.getSystemId();
658          if (systemId == null)
659          {
660             systemId = "null";
661          }
662          String JavaDoc info = "URI=" + systemId +
663                  " Line=" + spe.getLineNumber() +
664                  ": " + spe.getMessage();
665          return info;
666       }
667
668       // The following methods are standard SAX ErrorHandler methods.
669
// See SAX documentation for more info.
670

671       public void warning(SAXParseException JavaDoc spe) throws SAXException JavaDoc
672       {
673          if (log.isDebugEnabled())
674             log.debug(Messages.getMessage("warning00", getParseExceptionInfo(spe)));
675       }
676
677       public void error(SAXParseException JavaDoc spe) throws SAXException JavaDoc
678       {
679          String JavaDoc message = "Error: " + getParseExceptionInfo(spe);
680          throw new SAXException JavaDoc(message);
681       }
682
683       public void fatalError(SAXParseException JavaDoc spe) throws SAXException JavaDoc
684       {
685          String JavaDoc message = "Fatal Error: " + getParseExceptionInfo(spe);
686          throw new SAXException JavaDoc(message);
687       }
688    }
689
690
691    /**
692     * Utility to get the bytes uri.
693     * Does NOT handle authenticated URLs,
694     * use getInputSourceFromURI(uri, username, password)
695     *
696     * @param uri the resource to get
697     * @see #getInputSourceFromURI(String uri, String username, String password)
698     */

699    public static InputSource JavaDoc getInputSourceFromURI(String JavaDoc uri)
700    {
701       return new InputSource JavaDoc(uri);
702    }
703
704    /**
705     * Utility to get the bytes uri
706     *
707     * @param source the resource to get
708     */

709    public static InputSource JavaDoc sourceToInputSource(Source JavaDoc source)
710    {
711       if (source instanceof SAXSource JavaDoc)
712       {
713          return ((SAXSource JavaDoc)source).getInputSource();
714       }
715       else if (source instanceof DOMSource JavaDoc)
716       {
717          ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
718          Node JavaDoc node = ((DOMSource JavaDoc)source).getNode();
719          if (node instanceof Document JavaDoc)
720          {
721             node = ((Document JavaDoc)node).getDocumentElement();
722          }
723          Element JavaDoc domElement = (Element JavaDoc)node;
724          ElementToStream(domElement, baos);
725          InputSource JavaDoc isource = new InputSource JavaDoc(source.getSystemId());
726          isource.setByteStream(new ByteArrayInputStream JavaDoc(baos.toByteArray()));
727          return isource;
728       }
729       else if (source instanceof StreamSource JavaDoc)
730       {
731          StreamSource JavaDoc ss = (StreamSource JavaDoc)source;
732          InputSource JavaDoc isource = new InputSource JavaDoc(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    /**
745     * Utility to get the bytes at a protected uri
746     * <p/>
747     * This will retrieve the URL if a username and password are provided.
748     * The java.net.URL class does not do Basic Authentication, so we have to
749     * do it manually in this routine.
750     * <p/>
751     * If no username is provided, we create an InputSource from the uri
752     * and let the InputSource go fetch the contents.
753     *
754     * @param uri the resource to get
755     * @param username basic auth username
756     * @param password basic auth password
757     */

758    private static InputSource JavaDoc getInputSourceFromURI(String JavaDoc uri,
759                                                     String JavaDoc username,
760                                                     String JavaDoc password)
761            throws IOException JavaDoc, ProtocolException JavaDoc, UnsupportedEncodingException JavaDoc
762    {
763       URL JavaDoc wsdlurl = null;
764       try
765       {
766          wsdlurl = new URL JavaDoc(uri);
767       }
768       catch (MalformedURLException JavaDoc e)
769       {
770          // we can't process it, it might be a 'simple' foo.wsdl
771
// let InputSource deal with it
772
return new InputSource JavaDoc(uri);
773       }
774
775       // if no authentication, just let InputSource deal with it
776
if (username == null && wsdlurl.getUserInfo() == null)
777       {
778          return new InputSource JavaDoc(uri);
779       }
780
781       // if this is not an HTTP{S} url, let InputSource deal with it
782
if (!wsdlurl.getProtocol().startsWith("http"))
783       {
784          return new InputSource JavaDoc(uri);
785       }
786
787       URLConnection JavaDoc connection = wsdlurl.openConnection();
788       // Does this work for https???
789
if (!(connection instanceof HttpURLConnection JavaDoc))
790       {
791          // can't do http with this URL, let InputSource deal with it
792
return new InputSource JavaDoc(uri);
793       }
794       HttpURLConnection JavaDoc uconn = (HttpURLConnection JavaDoc)connection;
795       String JavaDoc 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       // username/password info in the URL overrides passed in values
805
String JavaDoc 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 JavaDoc(uconn.getInputStream());
825    }
826
827    public static final String JavaDoc base64encode(byte[] bytes)
828    {
829       return new String JavaDoc(Base64.encode(bytes));
830    }
831
832    public static InputSource JavaDoc getEmptyInputSource()
833    {
834       return new InputSource JavaDoc(bais);
835    }
836
837    /**
838     * Find a Node with a given QName
839     *
840     * @param node parent node
841     * @param name QName of the child we need to find
842     * @return child node
843     */

844    public static Node JavaDoc findNode(Node JavaDoc node, QName JavaDoc name)
845    {
846       if (name.getNamespaceURI().equals(node.getNamespaceURI()) &&
847               name.getLocalPart().equals(node.getLocalName()))
848          return node;
849       NodeList JavaDoc children = node.getChildNodes();
850       for (int i = 0; i < children.getLength(); i++)
851       {
852          Node JavaDoc ret = findNode(children.item(i), name);
853          if (ret != null)
854             return ret;
855       }
856       return null;
857    }
858
859    /**
860     * Trim all new lines from text nodes.
861     *
862     * @param node
863     */

864    public static void normalize(Node JavaDoc node)
865    {
866       if (node.getNodeType() == Node.TEXT_NODE)
867       {
868          String JavaDoc data = ((Text JavaDoc)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 JavaDoc data2 = trim(data);
875                ((Text JavaDoc)node).setData(data2);
876             }
877          }
878       }
879       for (Node JavaDoc currentChild = node.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling())
880       {
881          normalize(currentChild);
882       }
883    }
884
885    public static String JavaDoc trim(String JavaDoc 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    /**
919     * Converts a List with org.w3c.dom.Element objects to an Array
920     * with org.w3c.dom.Element objects.
921     *
922     * @param list List containing org.w3c.dom.Element objects
923     * @return Element[] Array with org.w3c.dom.Element objects
924     */

925    public static Element JavaDoc[] asElementArray(List JavaDoc list)
926    {
927
928       Element JavaDoc[] elements = new Element JavaDoc[list.size()];
929
930       int i = 0;
931       Iterator JavaDoc detailIter = list.iterator();
932       while (detailIter.hasNext())
933       {
934          elements[i++] = (Element JavaDoc)detailIter.next();
935       }
936
937       return elements;
938    }
939 }
940
Popular Tags