📄 xmlutils.java
字号:
/* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.axis.utils ;import org.apache.axis.AxisEngine;import org.apache.axis.Constants;import org.apache.axis.InternalException;import org.apache.axis.Message;import org.apache.axis.MessageContext;import org.apache.axis.AxisProperties;import org.apache.axis.components.encoding.XMLEncoder;import org.apache.axis.components.encoding.XMLEncoderFactory;import org.apache.axis.components.logger.LogFactory;import org.apache.commons.logging.Log;import org.w3c.dom.Attr;import org.w3c.dom.CharacterData;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.ErrorHandler;import org.xml.sax.InputSource;import org.xml.sax.SAXException;import org.xml.sax.SAXParseException;import org.xml.sax.XMLReader;import org.xml.sax.helpers.DefaultHandler;import javax.xml.namespace.QName;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import javax.xml.soap.SOAPException;import javax.xml.soap.SOAPMessage;import javax.xml.transform.Source;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.sax.SAXSource;import javax.xml.transform.stream.StreamSource;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.StringWriter;import java.io.UnsupportedEncodingException;import java.io.Writer;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;import java.net.URL;import java.net.URLConnection;import java.util.Iterator;import java.util.List;import java.util.Stack;public class XMLUtils { protected static Log log = LogFactory.getLog(XMLUtils.class.getName()); public static final String httpAuthCharEncoding = "ISO-8859-1"; private static final String saxParserFactoryProperty = "javax.xml.parsers.SAXParserFactory"; private static DocumentBuilderFactory dbf = getDOMFactory(); private static SAXParserFactory saxFactory; private static Stack saxParsers = new Stack(); private static DefaultHandler doNothingContentHandler = new DefaultHandler(); private static String EMPTY = ""; private static ByteArrayInputStream bais = new ByteArrayInputStream(EMPTY.getBytes()); private static boolean tryReset= true; protected static boolean enableParserReuse = false; private static class ThreadLocalDocumentBuilder extends ThreadLocal { protected Object initialValue() { try { return getDOMFactory().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error(Messages.getMessage("parserConfigurationException00"), e); } return null; } } private static ThreadLocalDocumentBuilder documentBuilder = new ThreadLocalDocumentBuilder(); static { // Initialize SAX Parser factory defaults initSAXFactory(null, true, false); String value = AxisProperties.getProperty(AxisEngine.PROP_XML_REUSE_SAX_PARSERS, "" + true); if (value.equalsIgnoreCase("true") || value.equals("1") || value.equalsIgnoreCase("yes")) { enableParserReuse = true; } else { enableParserReuse = false; } } /** * Encode a string appropriately for XML. * @param orig the String to encode * @return a String in which XML special chars are repalced by entities */ public static String xmlEncodeString(String orig) { XMLEncoder encoder = getXMLEncoder(MessageContext.getCurrentContext()); return encoder.encode(orig); } /** * Get the current XMLEncoder * @return XMLEncoder */ public static XMLEncoder getXMLEncoder(MessageContext msgContext) { return getXMLEncoder(getEncoding(null, msgContext)); } /** * Get the XMLEncoder for specific encoding * @return XMLEncoder */ public static XMLEncoder getXMLEncoder(String encoding) { XMLEncoder encoder = null; try { encoder = XMLEncoderFactory.getEncoder(encoding); } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); encoder = XMLEncoderFactory.getDefaultEncoder(); } return encoder; } /** * Get the current encoding in effect * @return string */ public static String getEncoding(MessageContext msgContext) { XMLEncoder encoder = getXMLEncoder(msgContext); return encoder.getEncoding(); } /** * Get the current encoding in effect * @return string */ public static String getEncoding() { XMLEncoder encoder = getXMLEncoder(MessageContext.getCurrentContext()); return encoder.getEncoding(); } /** Initialize the SAX parser factory. * * @param factoryClassName The (optional) class name of the desired * SAXParserFactory implementation. Will be * assigned to the system property * <b>javax.xml.parsers.SAXParserFactory</b> * unless this property is already set. * If <code>null</code>, leaves current setting * alone. * @param namespaceAware true if we want a namespace-aware parser * @param validating true if we want a validating parser * */ public static void initSAXFactory(String factoryClassName, boolean namespaceAware, boolean validating) { if (factoryClassName != null) { try { saxFactory = (SAXParserFactory)Class.forName(factoryClassName). newInstance(); /* * Set the system property only if it is not already set to * avoid corrupting environments in which Axis is embedded. */ if (System.getProperty(saxParserFactoryProperty) == null) { System.setProperty(saxParserFactoryProperty, factoryClassName); } } catch (Exception e) { log.error(Messages.getMessage("exception00"), e); saxFactory = null; } } else { saxFactory = SAXParserFactory.newInstance(); } saxFactory.setNamespaceAware(namespaceAware); saxFactory.setValidating(validating); // Discard existing parsers saxParsers.clear(); } private static DocumentBuilderFactory getDOMFactory() { DocumentBuilderFactory dbf; try { dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); } catch( Exception e ) { log.error(Messages.getMessage("exception00"), e ); dbf = null; } return( dbf ); } /** * Gets a DocumentBuilder * @return DocumentBuilder * @throws ParserConfigurationException */ public static DocumentBuilder getDocumentBuilder() throws ParserConfigurationException { return (DocumentBuilder) documentBuilder.get(); } /** * Releases a DocumentBuilder * @param db */ public static void releaseDocumentBuilder(DocumentBuilder db) { try { db.setErrorHandler(null); // setting implementation default } catch (Throwable t) { log.debug("Failed to set ErrorHandler to null on DocumentBuilder", t); } try { db.setEntityResolver(null); // setting implementation default } catch (Throwable t) { log.debug("Failed to set EntityResolver to null on DocumentBuilder", t); } } /** Get a SAX parser instance from the JAXP factory. * * @return a SAXParser instance. */ public static synchronized SAXParser getSAXParser() { if(enableParserReuse && !saxParsers.empty()) { return (SAXParser )saxParsers.pop(); } try { SAXParser parser = saxFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); // parser.getParser().setEntityResolver(new DefaultEntityResolver()); // The above commented line and the following line are added // for preventing XXE (bug #14105). // We may need to uncomment the deprecated setting // in case that it is considered necessary. try { reader.setEntityResolver(new DefaultEntityResolver()); } catch (Throwable t) { log.debug("Failed to set EntityResolver on DocumentBuilder", t); } reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false); return parser; } catch (ParserConfigurationException e) { log.error(Messages.getMessage("parserConfigurationException00"), e); return null; } catch (SAXException se) { log.error(Messages.getMessage("SAXException00"), se); return null; } } /** Return a SAX parser for reuse. * @param parser A SAX parser that is available for reuse */ public static void releaseSAXParser(SAXParser parser) { if(!tryReset || !enableParserReuse) return; //Free up possible ref. held by past contenthandler. try{ XMLReader xmlReader= parser.getXMLReader(); if(null != xmlReader){ xmlReader.setContentHandler(doNothingContentHandler); xmlReader.setDTDHandler(doNothingContentHandler); try { xmlReader.setEntityResolver(doNothingContentHandler); } catch (Throwable t) { log.debug("Failed to set EntityResolver on DocumentBuilder", t); } try { xmlReader.setErrorHandler(doNothingContentHandler); } catch (Throwable t) { log.debug("Failed to set ErrorHandler on DocumentBuilder", t); } synchronized (XMLUtils.class ) { saxParsers.push(parser); } } else { tryReset= false; } } catch (org.xml.sax.SAXException e) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -