1 /*
   2  * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package javax.xml.parsers;
  27 
  28 import java.io.File;
  29 import java.security.AccessController;
  30 import java.security.PrivilegedAction;
  31 import java.util.Properties;
  32 import java.util.ServiceConfigurationError;
  33 import java.util.ServiceLoader;
  34 
  35 /**
  36  * <p>Implements pluggable Datatypes.</p>
  37  *
  38  * <p>This class is duplicated for each JAXP subpackage so keep it in sync. It
  39  * is package private for secure class loading.</p>
  40  *
  41  * @author Santiago.PericasGeertsen@sun.com
  42  * @author Huizhe.Wang@oracle.com
  43  */
  44 class FactoryFinder {
  45 
  46     /**
  47      * Internal debug flag.
  48      */
  49     private static boolean debug = false;
  50     /**
  51      * Cache for properties in java.home/lib/jaxp.properties
  52      */
  53     static Properties cacheProps = new Properties();
  54     /**
  55      * Flag indicating if properties from java.home/lib/jaxp.properties have
  56      * been cached.
  57      */
  58     static volatile boolean firstTime = true;
  59     /**
  60      * Security support class use to check access control before getting certain
  61      * system resources.
  62      */
  63     static SecuritySupport ss = new SecuritySupport();
  64 
  65     // Define system property "jaxp.debug" to get output
  66     static {
  67         // Use try/catch block to support applets, which throws
  68         // SecurityException out of this code.
  69         try {
  70             String val = ss.getSystemProperty("jaxp.debug");
  71             // Allow simply setting the prop to turn on debug
  72             debug = val != null && !"false".equals(val);
  73         } catch (SecurityException se) {
  74             debug = false;
  75         }
  76     }
  77 
  78     private static void dPrint(String msg) {
  79         if (debug) {
  80             System.err.println("JAXP: " + msg);
  81         }
  82     }
  83 
  84     /**
  85      * Attempt to load a class using the class loader supplied. If that fails
  86      * and fall back is enabled, the current (i.e. bootstrap) class loader is
  87      * tried.
  88      *
  89      * If the class loader supplied is
  90      * <code>null</code>, first try using the context class loader followed by
  91      * the current (i.e. bootstrap) class loader.
  92      *
  93      * Use bootstrap classLoader if cl = null and useBSClsLoader is true
  94      */
  95     static private Class getProviderClass(String className, ClassLoader cl,
  96             boolean doFallback, boolean useBSClsLoader) throws ClassNotFoundException {
  97         try {
  98             if (cl == null) {
  99                 if (useBSClsLoader) {
 100                     return Class.forName(className, true, FactoryFinder.class.getClassLoader());
 101                 } else {
 102                     cl = ss.getContextClassLoader();
 103                     if (cl == null) {
 104                         throw new ClassNotFoundException();
 105                     } else {
 106                         return cl.loadClass(className);
 107                     }
 108                 }
 109             } else {
 110                 return cl.loadClass(className);
 111             }
 112         } catch (ClassNotFoundException e1) {
 113             if (doFallback) {
 114                 // Use current class loader - should always be bootstrap CL
 115                 return Class.forName(className, true, FactoryFinder.class.getClassLoader());
 116             } else {
 117                 throw e1;
 118             }
 119         }
 120     }
 121 
 122     /**
 123      * Create an instance of a class. Delegates to method
 124      * <code>getProviderClass()</code> in order to load the class.
 125      *
 126      * @param className Name of the concrete class corresponding to the service
 127      * provider
 128      *
 129      * @param cl <code>ClassLoader</code> used to load the factory class.
 130      * If <code>null</code> current <code>Thread</code>'s context classLoader is
 131      * used to load the factory class.
 132      *
 133      * @param doFallback True if the current ClassLoader should be tried as a
 134      * fallback if the class is not found using cl
 135      */
 136     static Object newInstance(String className, ClassLoader cl, boolean doFallback)
 137             throws FactoryConfigurationError {
 138         return newInstance(className, cl, doFallback, false);
 139     }
 140 
 141     /**
 142      * Create an instance of a class. Delegates to method
 143      * <code>getProviderClass()</code> in order to load the class.
 144      *
 145      * @param className Name of the concrete class corresponding to the service
 146      * provider
 147      *
 148      * @param cl <code>ClassLoader</code> used to load the factory class.
 149      * If <code>null</code> current <code>Thread</code>'s context classLoader is
 150      * used to load the factory class.
 151      *
 152      * @param doFallback True if the current ClassLoader should be tried as a
 153      * fallback if the class is not found using cl
 154      *
 155      * @param useBSClsLoader True if cl=null actually meant bootstrap
 156      * classLoader. This parameter is needed since
 157      * DocumentBuilderFactory/SAXParserFactory defined null as context
 158      * classLoader.
 159      */
 160     static Object newInstance(String className, ClassLoader cl, boolean doFallback, boolean useBSClsLoader)
 161             throws FactoryConfigurationError {
 162         try {
 163             Class providerClass = getProviderClass(className, cl, doFallback, useBSClsLoader);
 164             Object instance = providerClass.newInstance();
 165             if (debug) {    // Extra check to avoid computing cl strings
 166                 dPrint("created new instance of " + providerClass
 167                         + " using ClassLoader: " + cl);
 168             }
 169             return instance;
 170         } catch (ClassNotFoundException x) {
 171             throw new FactoryConfigurationError(x,
 172                     "Provider " + className + " not found");
 173         } catch (Exception x) {
 174             throw new FactoryConfigurationError(x,
 175                     "Provider " + className + " could not be instantiated: " + x);
 176         }
 177     }
 178 
 179     /**
 180      * Finds the implementation Class object in the specified order. Main entry
 181      * point.
 182      *
 183      * @return Class object of factory, never null
 184      *
 185      * @param factoryId Name of the factory to find, same as a property name
 186      * @param fallbackClassName Implementation class name, if nothing else is
 187      * found. Use null to mean no fallback.
 188      *
 189      * Package private so this code can be shared.
 190      */
 191     static Object find(Class factoryClass, String factoryId, String fallbackClassName)
 192             throws FactoryConfigurationError {
 193         dPrint("find factoryId =" + factoryId);
 194 
 195         // Use the system property first
 196         try {
 197             String systemProp = ss.getSystemProperty(factoryId);
 198             if (systemProp != null) {
 199                 dPrint("found system property, value=" + systemProp);
 200                 return newInstance(systemProp, null, true);
 201             }
 202         } catch (SecurityException se) {
 203             if (debug) {
 204                 se.printStackTrace();
 205             }
 206         }
 207 
 208         // try to read from $java.home/lib/jaxp.properties
 209         try {
 210             String factoryClassName = null;
 211             if (firstTime) {
 212                 synchronized (cacheProps) {
 213                     if (firstTime) {
 214                         String configFile = ss.getSystemProperty("java.home") + File.separator
 215                                 + "lib" + File.separator + "jaxp.properties";
 216                         File f = new File(configFile);
 217                         firstTime = false;
 218                         if (ss.doesFileExist(f)) {
 219                             dPrint("Read properties file " + f);
 220                             cacheProps.load(ss.getFileInputStream(f));
 221                         }
 222                     }
 223                 }
 224             }
 225             factoryClassName = cacheProps.getProperty(factoryId);
 226 
 227             if (factoryClassName != null) {
 228                 dPrint("found in $java.home/jaxp.properties, value=" + factoryClassName);
 229                 return newInstance(factoryClassName, null, true);
 230             }
 231         } catch (Exception ex) {
 232             if (debug) {
 233                 ex.printStackTrace();
 234             }
 235         }
 236 
 237         // Try service-provider loading facilities
 238         try {
 239             Object provider = findServiceProvider(factoryClass, fallbackClassName);
 240             if (provider != null) {
 241                 return provider;
 242             }
 243         } catch (FactoryConfigurationError e) {
 244             throw e;
 245         }
 246 
 247         // Last, check if fallback is requested
 248         if (fallbackClassName == null) {
 249             throw new FactoryConfigurationError("Provider for " + factoryId + " cannot be found");
 250         }
 251 
 252         dPrint("loaded from fallback value: " + fallbackClassName);
 253         return newInstance(fallbackClassName, null, true);
 254     }
 255 
 256     /*
 257      * Try to find a provider using Service Loader
 258      *
 259      * @return instance of provider class if found or null
 260      */
 261     private static Object findServiceProvider(final Class factoryClass, final String fallbackClassName)
 262             throws FactoryConfigurationError {
 263         try {
 264             return AccessController.doPrivileged(new PrivilegedAction() {
 265                 public Object run() {
 266                     Object defaultProvider = null;
 267                     for (Object factory : ServiceLoader.load(factoryClass)) {
 268                         if (factory.getClass().getName().equals(fallbackClassName)) {
 269                             defaultProvider = factory;
 270                         } else {
 271                             return factory;
 272                         }
 273                     }
 274                     if (defaultProvider != null) {
 275                         return defaultProvider;
 276                     }
 277                     return null;
 278                 }
 279             });
 280         } catch (ServiceConfigurationError e) {
 281             throw new FactoryConfigurationError((Exception) e.getCause(), e.getMessage());
 282         }
 283     }
 284 }