src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java

changeset 0
373ffda63c9a
child 637
9c07ef4934dd
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java	Wed Apr 27 01:27:09 2016 +0800
     1.3 @@ -0,0 +1,461 @@
     1.4 +/*
     1.5 + * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package com.sun.xml.internal.ws.util.xml;
    1.30 +
    1.31 +import com.sun.istack.internal.Nullable;
    1.32 +import com.sun.org.apache.xml.internal.resolver.Catalog;
    1.33 +import com.sun.org.apache.xml.internal.resolver.CatalogManager;
    1.34 +import com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver;
    1.35 +import com.sun.xml.internal.ws.server.ServerRtException;
    1.36 +import com.sun.xml.internal.ws.util.ByteArrayBuffer;
    1.37 +import org.w3c.dom.Attr;
    1.38 +import org.w3c.dom.Element;
    1.39 +import org.w3c.dom.EntityReference;
    1.40 +import org.w3c.dom.Node;
    1.41 +import org.w3c.dom.NodeList;
    1.42 +import org.w3c.dom.Text;
    1.43 +import org.xml.sax.*;
    1.44 +
    1.45 +import javax.xml.XMLConstants;
    1.46 +import javax.xml.namespace.QName;
    1.47 +import javax.xml.parsers.DocumentBuilderFactory;
    1.48 +import javax.xml.parsers.ParserConfigurationException;
    1.49 +import javax.xml.parsers.SAXParserFactory;
    1.50 +import javax.xml.stream.XMLInputFactory;
    1.51 +import javax.xml.transform.Result;
    1.52 +import javax.xml.transform.Source;
    1.53 +import javax.xml.transform.Transformer;
    1.54 +import javax.xml.transform.TransformerConfigurationException;
    1.55 +import javax.xml.transform.TransformerException;
    1.56 +import javax.xml.transform.TransformerFactory;
    1.57 +import javax.xml.transform.sax.SAXTransformerFactory;
    1.58 +import javax.xml.transform.sax.TransformerHandler;
    1.59 +import javax.xml.transform.stream.StreamSource;
    1.60 +import javax.xml.validation.SchemaFactory;
    1.61 +import javax.xml.ws.WebServiceException;
    1.62 +import javax.xml.xpath.XPathFactory;
    1.63 +import javax.xml.xpath.XPathFactoryConfigurationException;
    1.64 +import java.io.IOException;
    1.65 +import java.io.InputStream;
    1.66 +import java.io.OutputStreamWriter;
    1.67 +import java.io.Writer;
    1.68 +import java.net.URL;
    1.69 +import java.util.ArrayList;
    1.70 +import java.util.Enumeration;
    1.71 +import java.util.Iterator;
    1.72 +import java.util.List;
    1.73 +import java.util.StringTokenizer;
    1.74 +import java.util.logging.Level;
    1.75 +import java.util.logging.Logger;
    1.76 +
    1.77 +/**
    1.78 + * @author WS Development Team
    1.79 + */
    1.80 +public class XmlUtil {
    1.81 +
    1.82 +    // not in older JDK, so must be duplicated here, otherwise javax.xml.XMLConstants should be used
    1.83 +    private static final String ACCESS_EXTERNAL_SCHEMA = "http://javax.xml.XMLConstants/property/accessExternalSchema";
    1.84 +
    1.85 +    private final static String LEXICAL_HANDLER_PROPERTY =
    1.86 +        "http://xml.org/sax/properties/lexical-handler";
    1.87 +
    1.88 +    private static final Logger LOGGER = Logger.getLogger(XmlUtil.class.getName());
    1.89 +
    1.90 +    private static boolean XML_SECURITY_DISABLED;
    1.91 +
    1.92 +    static {
    1.93 +        String disableXmlSecurity = System.getProperty("com.sun.xml.internal.ws.disableXmlSecurity");
    1.94 +        XML_SECURITY_DISABLED = disableXmlSecurity == null || !Boolean.valueOf(disableXmlSecurity);
    1.95 +    }
    1.96 +
    1.97 +    public static String getPrefix(String s) {
    1.98 +        int i = s.indexOf(':');
    1.99 +        if (i == -1)
   1.100 +            return null;
   1.101 +        return s.substring(0, i);
   1.102 +    }
   1.103 +
   1.104 +    public static String getLocalPart(String s) {
   1.105 +        int i = s.indexOf(':');
   1.106 +        if (i == -1)
   1.107 +            return s;
   1.108 +        return s.substring(i + 1);
   1.109 +    }
   1.110 +
   1.111 +
   1.112 +
   1.113 +    public static String getAttributeOrNull(Element e, String name) {
   1.114 +        Attr a = e.getAttributeNode(name);
   1.115 +        if (a == null)
   1.116 +            return null;
   1.117 +        return a.getValue();
   1.118 +    }
   1.119 +
   1.120 +    public static String getAttributeNSOrNull(
   1.121 +        Element e,
   1.122 +        String name,
   1.123 +        String nsURI) {
   1.124 +        Attr a = e.getAttributeNodeNS(nsURI, name);
   1.125 +        if (a == null)
   1.126 +            return null;
   1.127 +        return a.getValue();
   1.128 +    }
   1.129 +
   1.130 +    public static String getAttributeNSOrNull(
   1.131 +        Element e,
   1.132 +        QName name) {
   1.133 +        Attr a = e.getAttributeNodeNS(name.getNamespaceURI(), name.getLocalPart());
   1.134 +        if (a == null)
   1.135 +            return null;
   1.136 +        return a.getValue();
   1.137 +    }
   1.138 +
   1.139 +/*    public static boolean matchesTagNS(Element e, String tag, String nsURI) {
   1.140 +        try {
   1.141 +            return e.getLocalName().equals(tag)
   1.142 +                && e.getNamespaceURI().equals(nsURI);
   1.143 +        } catch (NullPointerException npe) {
   1.144 +
   1.145 +            // localname not null since parsing would fail before here
   1.146 +            throw new WSDLParseException(
   1.147 +                "null.namespace.found",
   1.148 +                e.getLocalName());
   1.149 +        }
   1.150 +    }
   1.151 +
   1.152 +    public static boolean matchesTagNS(
   1.153 +        Element e,
   1.154 +        javax.xml.namespace.QName name) {
   1.155 +        try {
   1.156 +            return e.getLocalName().equals(name.getLocalPart())
   1.157 +                && e.getNamespaceURI().equals(name.getNamespaceURI());
   1.158 +        } catch (NullPointerException npe) {
   1.159 +
   1.160 +            // localname not null since parsing would fail before here
   1.161 +            throw new WSDLParseException(
   1.162 +                "null.namespace.found",
   1.163 +                e.getLocalName());
   1.164 +        }
   1.165 +    }*/
   1.166 +
   1.167 +    public static Iterator getAllChildren(Element element) {
   1.168 +        return new NodeListIterator(element.getChildNodes());
   1.169 +    }
   1.170 +
   1.171 +    public static Iterator getAllAttributes(Element element) {
   1.172 +        return new NamedNodeMapIterator(element.getAttributes());
   1.173 +    }
   1.174 +
   1.175 +    public static List<String> parseTokenList(String tokenList) {
   1.176 +        List<String> result = new ArrayList<String>();
   1.177 +        StringTokenizer tokenizer = new StringTokenizer(tokenList, " ");
   1.178 +        while (tokenizer.hasMoreTokens()) {
   1.179 +            result.add(tokenizer.nextToken());
   1.180 +        }
   1.181 +        return result;
   1.182 +    }
   1.183 +
   1.184 +    public static String getTextForNode(Node node) {
   1.185 +        StringBuilder sb = new StringBuilder();
   1.186 +
   1.187 +        NodeList children = node.getChildNodes();
   1.188 +        if (children.getLength() == 0)
   1.189 +            return null;
   1.190 +
   1.191 +        for (int i = 0; i < children.getLength(); ++i) {
   1.192 +            Node n = children.item(i);
   1.193 +
   1.194 +            if (n instanceof Text)
   1.195 +                sb.append(n.getNodeValue());
   1.196 +            else if (n instanceof EntityReference) {
   1.197 +                String s = getTextForNode(n);
   1.198 +                if (s == null)
   1.199 +                    return null;
   1.200 +                else
   1.201 +                    sb.append(s);
   1.202 +            } else
   1.203 +                return null;
   1.204 +        }
   1.205 +
   1.206 +        return sb.toString();
   1.207 +    }
   1.208 +
   1.209 +    public static InputStream getUTF8Stream(String s) {
   1.210 +        try {
   1.211 +            ByteArrayBuffer bab = new ByteArrayBuffer();
   1.212 +            Writer w = new OutputStreamWriter(bab, "utf-8");
   1.213 +            w.write(s);
   1.214 +            w.close();
   1.215 +            return bab.newInputStream();
   1.216 +        } catch (IOException e) {
   1.217 +            throw new RuntimeException("should not happen");
   1.218 +        }
   1.219 +    }
   1.220 +
   1.221 +    static final ContextClassloaderLocal<TransformerFactory> transformerFactory = new ContextClassloaderLocal<TransformerFactory>() {
   1.222 +        @Override
   1.223 +        protected TransformerFactory initialValue() throws Exception {
   1.224 +            return TransformerFactory.newInstance();
   1.225 +        }
   1.226 +    };
   1.227 +
   1.228 +    static final ContextClassloaderLocal<SAXParserFactory> saxParserFactory = new ContextClassloaderLocal<SAXParserFactory>() {
   1.229 +        @Override
   1.230 +        protected SAXParserFactory initialValue() throws Exception {
   1.231 +            SAXParserFactory factory = SAXParserFactory.newInstance();
   1.232 +            factory.setNamespaceAware(true);
   1.233 +            return factory;
   1.234 +        }
   1.235 +    };
   1.236 +
   1.237 +    /**
   1.238 +     * Creates a new identity transformer.
   1.239 +     */
   1.240 +    public static Transformer newTransformer() {
   1.241 +        try {
   1.242 +            return transformerFactory.get().newTransformer();
   1.243 +        } catch (TransformerConfigurationException tex) {
   1.244 +            throw new IllegalStateException("Unable to create a JAXP transformer");
   1.245 +        }
   1.246 +    }
   1.247 +
   1.248 +    /**
   1.249 +     * Performs identity transformation.
   1.250 +     */
   1.251 +    public static <T extends Result>
   1.252 +    T identityTransform(Source src, T result) throws TransformerException, SAXException, ParserConfigurationException, IOException {
   1.253 +        if (src instanceof StreamSource) {
   1.254 +            // work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
   1.255 +            // is not turned on by default
   1.256 +            StreamSource ssrc = (StreamSource) src;
   1.257 +            TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
   1.258 +            th.setResult(result);
   1.259 +            XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
   1.260 +            reader.setContentHandler(th);
   1.261 +            reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
   1.262 +            reader.parse(toInputSource(ssrc));
   1.263 +        } else {
   1.264 +            newTransformer().transform(src, result);
   1.265 +        }
   1.266 +        return result;
   1.267 +    }
   1.268 +
   1.269 +    private static InputSource toInputSource(StreamSource src) {
   1.270 +        InputSource is = new InputSource();
   1.271 +        is.setByteStream(src.getInputStream());
   1.272 +        is.setCharacterStream(src.getReader());
   1.273 +        is.setPublicId(src.getPublicId());
   1.274 +        is.setSystemId(src.getSystemId());
   1.275 +        return is;
   1.276 +    }
   1.277 +
   1.278 +    /*
   1.279 +    * Gets an EntityResolver using XML catalog
   1.280 +    */
   1.281 +     public static EntityResolver createEntityResolver(@Nullable URL catalogUrl) {
   1.282 +        // set up a manager
   1.283 +        CatalogManager manager = new CatalogManager();
   1.284 +        manager.setIgnoreMissingProperties(true);
   1.285 +        // Using static catalog may  result in to sharing of the catalog by multiple apps running in a container
   1.286 +        manager.setUseStaticCatalog(false);
   1.287 +        Catalog catalog = manager.getCatalog();
   1.288 +        try {
   1.289 +            if (catalogUrl != null) {
   1.290 +                catalog.parseCatalog(catalogUrl);
   1.291 +            }
   1.292 +        } catch (IOException e) {
   1.293 +            throw new ServerRtException("server.rt.err",e);
   1.294 +        }
   1.295 +        return workaroundCatalogResolver(catalog);
   1.296 +    }
   1.297 +
   1.298 +    /**
   1.299 +     * Gets a default EntityResolver for catalog at META-INF/jaxws-catalog.xml
   1.300 +     */
   1.301 +    public static EntityResolver createDefaultCatalogResolver() {
   1.302 +
   1.303 +        // set up a manager
   1.304 +        CatalogManager manager = new CatalogManager();
   1.305 +        manager.setIgnoreMissingProperties(true);
   1.306 +        // Using static catalog may  result in to sharing of the catalog by multiple apps running in a container
   1.307 +        manager.setUseStaticCatalog(false);
   1.308 +        // parse the catalog
   1.309 +        ClassLoader cl = Thread.currentThread().getContextClassLoader();
   1.310 +        Enumeration<URL> catalogEnum;
   1.311 +        Catalog catalog = manager.getCatalog();
   1.312 +        try {
   1.313 +            if (cl == null) {
   1.314 +                catalogEnum = ClassLoader.getSystemResources("META-INF/jax-ws-catalog.xml");
   1.315 +            } else {
   1.316 +                catalogEnum = cl.getResources("META-INF/jax-ws-catalog.xml");
   1.317 +            }
   1.318 +
   1.319 +            while(catalogEnum.hasMoreElements()) {
   1.320 +                URL url = catalogEnum.nextElement();
   1.321 +                catalog.parseCatalog(url);
   1.322 +            }
   1.323 +        } catch (IOException e) {
   1.324 +            throw new WebServiceException(e);
   1.325 +        }
   1.326 +
   1.327 +        return workaroundCatalogResolver(catalog);
   1.328 +    }
   1.329 +
   1.330 +    /**
   1.331 +     *  Default CatalogResolver implementation is broken as it depends on CatalogManager.getCatalog() which will always create a new one when
   1.332 +     *  useStaticCatalog is false.
   1.333 +     *  This returns a CatalogResolver that uses the catalog passed as parameter.
   1.334 +     * @param catalog
   1.335 +     * @return  CatalogResolver
   1.336 +     */
   1.337 +    private static CatalogResolver workaroundCatalogResolver(final Catalog catalog) {
   1.338 +        // set up a manager
   1.339 +        CatalogManager manager = new CatalogManager() {
   1.340 +            @Override
   1.341 +            public Catalog getCatalog() {
   1.342 +                return catalog;
   1.343 +            }
   1.344 +        };
   1.345 +        manager.setIgnoreMissingProperties(true);
   1.346 +        // Using static catalog may  result in to sharing of the catalog by multiple apps running in a container
   1.347 +        manager.setUseStaticCatalog(false);
   1.348 +
   1.349 +        return new CatalogResolver(manager);
   1.350 +    }
   1.351 +
   1.352 +    /**
   1.353 +     * {@link ErrorHandler} that always treat the error as fatal.
   1.354 +     */
   1.355 +    public static final ErrorHandler DRACONIAN_ERROR_HANDLER = new ErrorHandler() {
   1.356 +        @Override
   1.357 +        public void warning(SAXParseException exception) {
   1.358 +        }
   1.359 +
   1.360 +        @Override
   1.361 +        public void error(SAXParseException exception) throws SAXException {
   1.362 +            throw exception;
   1.363 +        }
   1.364 +
   1.365 +        @Override
   1.366 +        public void fatalError(SAXParseException exception) throws SAXException {
   1.367 +            throw exception;
   1.368 +        }
   1.369 +    };
   1.370 +
   1.371 +    public static DocumentBuilderFactory newDocumentBuilderFactory() {
   1.372 +        return newDocumentBuilderFactory(true);
   1.373 +    }
   1.374 +
   1.375 +    public static DocumentBuilderFactory newDocumentBuilderFactory(boolean secureXmlProcessing) {
   1.376 +        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   1.377 +        try {
   1.378 +            factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessing));
   1.379 +        } catch (ParserConfigurationException e) {
   1.380 +            LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } );
   1.381 +        }
   1.382 +        return factory;
   1.383 +    }
   1.384 +
   1.385 +    public static TransformerFactory newTransformerFactory(boolean secureXmlProcessingEnabled) {
   1.386 +        TransformerFactory factory = TransformerFactory.newInstance();
   1.387 +        try {
   1.388 +            factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessingEnabled));
   1.389 +        } catch (TransformerConfigurationException e) {
   1.390 +            LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[]{factory.getClass().getName()});
   1.391 +        }
   1.392 +        return factory;
   1.393 +    }
   1.394 +
   1.395 +    public static TransformerFactory newTransformerFactory() {
   1.396 +        return newTransformerFactory(true);
   1.397 +    }
   1.398 +
   1.399 +    public static SAXParserFactory newSAXParserFactory(boolean secureXmlProcessingEnabled) {
   1.400 +        SAXParserFactory factory = SAXParserFactory.newInstance();
   1.401 +        try {
   1.402 +            factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessingEnabled));
   1.403 +        } catch (Exception e) {
   1.404 +            LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[]{factory.getClass().getName()});
   1.405 +        }
   1.406 +        return factory;
   1.407 +    }
   1.408 +
   1.409 +    public static XPathFactory newXPathFactory(boolean secureXmlProcessingEnabled) {
   1.410 +        XPathFactory factory = XPathFactory.newInstance();
   1.411 +        try {
   1.412 +            factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessingEnabled));
   1.413 +        } catch (XPathFactoryConfigurationException e) {
   1.414 +            LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } );
   1.415 +        }
   1.416 +        return factory;
   1.417 +    }
   1.418 +
   1.419 +    public static XMLInputFactory newXMLInputFactory(boolean secureXmlProcessingEnabled)  {
   1.420 +        XMLInputFactory factory = XMLInputFactory.newInstance();
   1.421 +        if (isXMLSecurityDisabled(secureXmlProcessingEnabled)) {
   1.422 +            // TODO-Miran: are those apppropriate defaults?
   1.423 +            factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
   1.424 +            factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
   1.425 +        }
   1.426 +        return factory;
   1.427 +    }
   1.428 +
   1.429 +    private static boolean isXMLSecurityDisabled(boolean runtimeDisabled) {
   1.430 +        return XML_SECURITY_DISABLED || runtimeDisabled;
   1.431 +    }
   1.432 +
   1.433 +    public static SchemaFactory allowExternalAccess(SchemaFactory sf, String value, boolean disableSecureProcessing) {
   1.434 +
   1.435 +        // if xml security (feature secure processing) disabled, nothing to do, no restrictions applied
   1.436 +        if (isXMLSecurityDisabled(disableSecureProcessing)) {
   1.437 +            if (LOGGER.isLoggable(Level.FINE)) {
   1.438 +                LOGGER.log(Level.FINE, "Xml Security disabled, no JAXP xsd external access configuration necessary.");
   1.439 +            }
   1.440 +            return sf;
   1.441 +        }
   1.442 +
   1.443 +        if (System.getProperty("javax.xml.accessExternalSchema") != null) {
   1.444 +            if (LOGGER.isLoggable(Level.FINE)) {
   1.445 +                LOGGER.log(Level.FINE, "Detected explicitly JAXP configuration, no JAXP xsd external access configuration necessary.");
   1.446 +            }
   1.447 +            return sf;
   1.448 +        }
   1.449 +
   1.450 +        try {
   1.451 +            sf.setProperty(ACCESS_EXTERNAL_SCHEMA, value);
   1.452 +            if (LOGGER.isLoggable(Level.FINE)) {
   1.453 +                LOGGER.log(Level.FINE, "Property \"{0}\" is supported and has been successfully set by used JAXP implementation.", new Object[]{ACCESS_EXTERNAL_SCHEMA});
   1.454 +            }
   1.455 +        } catch (SAXException ignored) {
   1.456 +            // nothing to do; support depends on version JDK or SAX implementation
   1.457 +            if (LOGGER.isLoggable(Level.CONFIG)) {
   1.458 +                LOGGER.log(Level.CONFIG, "Property \"{0}\" is not supported by used JAXP implementation.", new Object[]{ACCESS_EXTERNAL_SCHEMA});
   1.459 +            }
   1.460 +        }
   1.461 +        return sf;
   1.462 +    }
   1.463 +
   1.464 +}

mercurial