Path: blob/aarch64-shenandoah-jdk8u272-b10/jaxp/src/javax/xml/xpath/XPathFactoryFinder.java
32285 views
/*1* Copyright (c) 2004, 2017, 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.net.URL;30import java.security.AccessControlContext;31import java.security.AccessController;32import java.security.PrivilegedAction;33import java.util.Properties;34import java.util.ServiceConfigurationError;35import java.util.ServiceLoader;3637/**38* Implementation of {@link XPathFactory#newInstance(String)}.39*40* @author <a href="[email protected]">Kohsuke Kawaguchi</a>41* @version $Revision: 1.7 $, $Date: 2010-11-01 04:36:14 $42* @since 1.543*/44class XPathFactoryFinder {45private static final String DEFAULT_PACKAGE = "com.sun.org.apache.xpath.internal";4647private static final SecuritySupport ss = new SecuritySupport() ;48/** debug support code. */49private static boolean debug = false;50static {51// Use try/catch block to support applets52try {53debug = ss.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 msg to print73*/74private static void debugPrintln(String msg) {75if (debug) {76System.err.println("JAXP: " + msg);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 == ss.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 = ss.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 = ss.getSystemProperty( "java.home" );177String configFile = javah + File.separator +178"lib" + File.separator + "jaxp.properties";179180// try to read from $java.home/lib/jaxp.properties181try {182if(firstTime){183synchronized(cacheProps){184if(firstTime){185File f=new File( configFile );186firstTime = false;187if(ss.doesFileExist(f)){188debugPrintln("Read properties file " + f);189cacheProps.load(ss.getFileInputStream(f));190}191}192}193}194final String factoryClassName = cacheProps.getProperty(propertyName);195debugPrintln("found " + factoryClassName + " in $java.home/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*/236private Class<?> createClass(String className) {237Class clazz;238// make sure we have access to restricted packages239boolean internal = false;240if (System.getSecurityManager() != null) {241if (className != null && className.startsWith(DEFAULT_PACKAGE)) {242internal = true;243}244}245246// use approprite ClassLoader247try {248if (classLoader != null && !internal) {249clazz = Class.forName(className, false, classLoader);250} else {251clazz = Class.forName(className);252}253} catch (Throwable t) {254if(debug) {255t.printStackTrace();256}257return null;258}259260return clazz;261}262263/**264* <p>Creates an instance of the specified and returns it.</p>265*266* @param className267* fully qualified class name to be instantiated.268*269* @return null270* if it fails. Error messages will be printed by this method.271*/272XPathFactory createInstance(String className)273throws XPathFactoryConfigurationException274{275XPathFactory xPathFactory = null;276277debugPrintln("createInstance(" + className + ")");278279// get Class from className280Class<?> clazz = createClass(className);281if (clazz == null) {282debugPrintln("failed to getClass(" + className + ")");283return null;284}285debugPrintln("loaded " + className + " from " + which(clazz));286287// instantiate Class as a XPathFactory288try {289xPathFactory = (XPathFactory) clazz.newInstance();290} catch (ClassCastException classCastException) {291debugPrintln("could not instantiate " + clazz.getName());292if (debug) {293classCastException.printStackTrace();294}295return null;296} catch (IllegalAccessException illegalAccessException) {297debugPrintln("could not instantiate " + clazz.getName());298if (debug) {299illegalAccessException.printStackTrace();300}301return null;302} catch (InstantiationException instantiationException) {303debugPrintln("could not instantiate " + clazz.getName());304if (debug) {305instantiationException.printStackTrace();306}307return null;308}309310return xPathFactory;311}312313// Call isObjectModelSupportedBy with initial context.314private boolean isObjectModelSupportedBy(final XPathFactory factory,315final String objectModel,316AccessControlContext acc) {317return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {318public Boolean run() {319return factory.isObjectModelSupported(objectModel);320}321}, acc);322}323324/**325* Finds a service provider subclass of XPathFactory that supports the326* given object model using the ServiceLoader.327*328* @param objectModel URI of object model to support.329* @return An XPathFactory supporting the specified object model, or null330* if none is found.331* @throws XPathFactoryConfigurationException if a configuration error is found.332*/333private XPathFactory findServiceProvider(final String objectModel)334throws XPathFactoryConfigurationException {335336assert objectModel != null;337// store current context.338final AccessControlContext acc = AccessController.getContext();339try {340return AccessController.doPrivileged(new PrivilegedAction<XPathFactory>() {341public XPathFactory run() {342final ServiceLoader<XPathFactory> loader =343ServiceLoader.load(SERVICE_CLASS);344for (XPathFactory factory : loader) {345// restore initial context to call346// factory.isObjectModelSupportedBy347if (isObjectModelSupportedBy(factory, objectModel, acc)) {348return factory;349}350}351return null; // no factory found.352}353});354} catch (ServiceConfigurationError error) {355throw new XPathFactoryConfigurationException(error);356}357}358359private static final Class<XPathFactory> SERVICE_CLASS = XPathFactory.class;360361private static String which( Class clazz ) {362return which( clazz.getName(), clazz.getClassLoader() );363}364365/**366* <p>Search the specified classloader for the given classname.</p>367*368* @param classname the fully qualified name of the class to search for369* @param loader the classloader to search370*371* @return the source location of the resource, or null if it wasn't found372*/373private static String which(String classname, ClassLoader loader) {374375String classnameAsResource = classname.replace('.', '/') + ".class";376377if( loader==null ) loader = ClassLoader.getSystemClassLoader();378379//URL it = loader.getResource(classnameAsResource);380URL it = ss.getResourceAsURL(loader, classnameAsResource);381if (it != null) {382return it.toString();383} else {384return null;385}386}387}388389390