Path: blob/master/src/java.xml/share/classes/javax/xml/xpath/XPathFactoryFinder.java
40948 views
/*1* Copyright (c) 2004, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package javax.xml.xpath;2627import com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl;28import java.io.File;29import java.lang.reflect.InvocationTargetException;30import java.security.AccessControlContext;31import java.security.AccessController;32import java.security.PrivilegedAction;33import java.util.Properties;34import java.util.ServiceConfigurationError;35import java.util.ServiceLoader;36import java.util.function.Supplier;37import jdk.xml.internal.SecuritySupport;3839/**40* Implementation of {@link XPathFactory#newInstance(String)}.41*42* @author Kohsuke Kawaguchi43* @since 1.544*/45class XPathFactoryFinder {46private static final String DEFAULT_PACKAGE = "com.sun.org.apache.xpath.internal";4748/** debug support code. */49private static boolean debug = false;50static {51// Use try/catch block to support applets52try {53debug = SecuritySupport.getSystemProperty("jaxp.debug") != null;54} catch (Exception unused) {55debug = false;56}57}5859/**60* <p>Cache properties for performance.</p>61*/62private static final Properties cacheProps = new Properties();6364/**65* <p>First time requires initialization overhead.</p>66*/67private volatile static boolean firstTime = true;6869/**70* <p>Conditional debug printing.</p>71*72* @param msgGen Supplier function that returns debug message73*/74private static void debugPrintln(Supplier<String> msgGen) {75if (debug) {76System.err.println("JAXP: " + msgGen.get());77}78}7980/**81* <p><code>ClassLoader</code> to use to find <code>XPathFactory</code>.</p>82*/83private final ClassLoader classLoader;8485/**86* <p>Constructor that specifies <code>ClassLoader</code> to use87* to find <code>XPathFactory</code>.</p>88*89* @param loader90* to be used to load resource and {@link XPathFactory}91* implementations during the resolution process.92* If this parameter is null, the default system class loader93* will be used.94*/95public XPathFactoryFinder(ClassLoader loader) {96this.classLoader = loader;97if( debug ) {98debugDisplayClassLoader();99}100}101102private void debugDisplayClassLoader() {103try {104if( classLoader == SecuritySupport.getContextClassLoader() ) {105debugPrintln(() -> "using thread context class loader ("+classLoader+") for search");106return;107}108} catch( Throwable unused ) {109// getContextClassLoader() undefined in JDK1.1110}111112if( classLoader==ClassLoader.getSystemClassLoader() ) {113debugPrintln(() -> "using system class loader ("+classLoader+") for search");114return;115}116117debugPrintln(() -> "using class loader ("+classLoader+") for search");118}119120/**121* <p>Creates a new {@link XPathFactory} object for the specified122* object model.</p>123*124* @param uri125* Identifies the underlying object model.126*127* @return <code>null</code> if the callee fails to create one.128*129* @throws NullPointerException130* If the parameter is null.131*/132public XPathFactory newFactory(String uri) throws XPathFactoryConfigurationException {133if (uri == null) {134throw new NullPointerException();135}136XPathFactory f = _newFactory(uri);137if (f != null) {138debugPrintln(()->"factory '" + f.getClass().getName() + "' was found for " + uri);139} else {140debugPrintln(()->"unable to find a factory for " + uri);141}142return f;143}144145/**146* <p>Lookup a {@link XPathFactory} for the given object model.</p>147*148* @param uri identifies the object model.149*150* @return {@link XPathFactory} for the given object model.151*/152private XPathFactory _newFactory(String uri) throws XPathFactoryConfigurationException {153XPathFactory xpathFactory = null;154155String propertyName = SERVICE_CLASS.getName() + ":" + uri;156157// system property look up158try {159debugPrintln(()->"Looking up system property '"+propertyName+"'" );160String r = SecuritySupport.getSystemProperty(propertyName);161if(r!=null) {162debugPrintln(()->"The value is '"+r+"'");163xpathFactory = createInstance(r);164if (xpathFactory != null) {165return xpathFactory;166}167} else168debugPrintln(()->"The property is undefined.");169} catch( Throwable t ) {170if( debug ) {171debugPrintln(()->"failed to look up system property '"+propertyName+"'" );172t.printStackTrace();173}174}175176String javah = SecuritySupport.getSystemProperty( "java.home" );177String configFile = javah + File.separator +178"conf" + File.separator + "jaxp.properties";179180// try to read from $java.home/conf/jaxp.properties181try {182if(firstTime){183synchronized(cacheProps){184if(firstTime){185File f=new File( configFile );186firstTime = false;187if(SecuritySupport.doesFileExist(f)){188debugPrintln(()->"Read properties file " + f);189cacheProps.load(SecuritySupport.getFileInputStream(f));190}191}192}193}194final String factoryClassName = cacheProps.getProperty(propertyName);195debugPrintln(()->"found " + factoryClassName + " in $java.home/conf/jaxp.properties");196197if (factoryClassName != null) {198xpathFactory = createInstance(factoryClassName);199if(xpathFactory != null){200return xpathFactory;201}202}203} catch (Exception ex) {204if (debug) {205ex.printStackTrace();206}207}208209// Try with ServiceLoader210assert xpathFactory == null;211xpathFactory = findServiceProvider(uri);212213// The following assertion should always be true.214// Uncomment it, recompile, and run with -ea in case of doubts:215// assert xpathFactory == null || xpathFactory.isObjectModelSupported(uri);216217if (xpathFactory != null) {218return xpathFactory;219}220221// platform default222if(uri.equals(XPathFactory.DEFAULT_OBJECT_MODEL_URI)) {223debugPrintln(()->"attempting to use the platform default W3C DOM XPath lib");224return new XPathFactoryImpl();225}226227debugPrintln(()->"all things were tried, but none was found. bailing out.");228return null;229}230231/** <p>Create class using appropriate ClassLoader.</p>232*233* @param className Name of class to create.234* @return Created class or <code>null</code>.235*/236@SuppressWarnings("removal")237private Class<?> createClass(String className) {238Class<?> clazz;239// make sure we have access to restricted packages240boolean internal = false;241if (System.getSecurityManager() != null) {242if (className != null && className.startsWith(DEFAULT_PACKAGE)) {243internal = true;244}245}246247// use approprite ClassLoader248try {249if (classLoader != null && !internal) {250clazz = Class.forName(className, false, classLoader);251} else {252clazz = Class.forName(className);253}254} catch (Throwable t) {255if(debug) {256t.printStackTrace();257}258return null;259}260261return clazz;262}263264/**265* <p>Creates an instance of the specified and returns it.</p>266*267* @param className268* fully qualified class name to be instantiated.269*270* @return null271* if it fails. Error messages will be printed by this method.272*/273XPathFactory createInstance(String className)274throws XPathFactoryConfigurationException275{276XPathFactory xPathFactory = null;277278debugPrintln(()->"createInstance(" + className + ")");279280// get Class from className281Class<?> clazz = createClass(className);282if (clazz == null) {283debugPrintln(()->"failed to getClass(" + className + ")");284return null;285}286debugPrintln(()->"loaded " + className + " from " + which(clazz));287288// instantiate Class as a XPathFactory289try {290xPathFactory = (XPathFactory) clazz.getConstructor().newInstance();291} catch (ClassCastException | IllegalAccessException | IllegalArgumentException |292InstantiationException | InvocationTargetException | NoSuchMethodException |293SecurityException ex) {294debugPrintln(()->"could not instantiate " + clazz.getName());295if (debug) {296ex.printStackTrace();297}298return null;299}300301return xPathFactory;302}303304// Call isObjectModelSupportedBy with initial context.305@SuppressWarnings("removal")306private boolean isObjectModelSupportedBy(final XPathFactory factory,307final String objectModel,308AccessControlContext acc) {309return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {310public Boolean run() {311return factory.isObjectModelSupported(objectModel);312}313}, acc);314}315316/**317* Finds a service provider subclass of XPathFactory that supports the318* given object model using the ServiceLoader.319*320* @param objectModel URI of object model to support.321* @return An XPathFactory supporting the specified object model, or null322* if none is found.323* @throws XPathFactoryConfigurationException if a configuration error is found.324*/325@SuppressWarnings("removal")326private XPathFactory findServiceProvider(final String objectModel)327throws XPathFactoryConfigurationException {328329assert objectModel != null;330// store current context.331final AccessControlContext acc = AccessController.getContext();332try {333return AccessController.doPrivileged(new PrivilegedAction<XPathFactory>() {334public XPathFactory run() {335final ServiceLoader<XPathFactory> loader =336ServiceLoader.load(SERVICE_CLASS);337for (XPathFactory factory : loader) {338// restore initial context to call339// factory.isObjectModelSupportedBy340if (isObjectModelSupportedBy(factory, objectModel, acc)) {341return factory;342}343}344return null; // no factory found.345}346});347} catch (ServiceConfigurationError error) {348throw new XPathFactoryConfigurationException(error);349}350}351352private static final Class<XPathFactory> SERVICE_CLASS = XPathFactory.class;353354// Used for debugging purposes355private static String which( Class<?> clazz ) {356return SecuritySupport.getClassSource(clazz);357}358359}360361362