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.Iterator;
  32 import java.util.Properties;
  33 import java.util.ServiceConfigurationError;
  34 import java.util.ServiceLoader;
  35 
  36 /**
  37  * <p>Implements pluggable Parsers.</p>
  38  *
  39  * <p>This class is duplicated for each JAXP subpackage so keep it in
  40  * sync.  It is package private for secure class loading.</p>
  41  *
  42  * @author Santiago.PericasGeertsen@sun.com
  43  * @author Huizhe.Wang@oracle.com
  44  */
  45 class FactoryFinder {
  46 
  47     /**
  48      * Internal debug flag.
  49      */
  50     private static boolean debug = false;
  51 
  52     /**
  53      * Cache for properties in java.home/lib/jaxp.properties
  54      */
  55     private static final Properties cacheProps = new Properties();
  56 
  57     /**
  58      * Flag indicating if properties from java.home/lib/jaxp.properties
  59      * have been cached.
  60      */
  61     static volatile boolean firstTime = true;
  62 
  63     /**
  64      * Security support class use to check access control before
  65      * getting certain system resources.
  66      */
  67     private static final SecuritySupport ss = new SecuritySupport();
  68 
  69     // Define system property "jaxp.debug" to get output
  70     static {
  71         // Use try/catch block to support applets, which throws
  72         // SecurityException out of this code.
  73         try {
  74             String val = ss.getSystemProperty("jaxp.debug");
  75             // Allow simply setting the prop to turn on debug
  76             debug = val != null && !"false".equals(val);
  77         }
  78         catch (SecurityException se) {
  79             debug = false;
  80         }
  81     }
  82 
  83     private static void dPrint(String msg) {
  84         if (debug) {
  85             System.err.println("JAXP: " + msg);
  86         }
  87     }
  88 
  89     /**
  90      * Attempt to load a class using the class loader supplied. If that fails
  91      * and fall back is enabled, the current (i.e. bootstrap) class loader is
  92      * tried.
  93      *
  94      * If the class loader supplied is <code>null</code>, first try using the
  95      * context class loader followed by the current (i.e. bootstrap) class
  96      * loader.
  97      *
  98      * Use bootstrap classLoader if cl = null and useBSClsLoader is true
  99      */
 100     static private Class<?> getProviderClass(String className, ClassLoader cl,
 101             boolean doFallback, boolean useBSClsLoader) throws ClassNotFoundException
 102     {
 103         try {
 104             if (cl == null) {
 105                 if (useBSClsLoader) {
 106                     return Class.forName(className, true, FactoryFinder.class.getClassLoader());
 107                 } else {
 108                     cl = ss.getContextClassLoader();
 109                     if (cl == null) {
 110                         throw new ClassNotFoundException();
 111                     }
 112                     else {
 113                         return Class.forName(className, false, cl);
 114                     }
 115                 }
 116             }
 117             else {
 118                 return Class.forName(className, false, cl);
 119             }
 120         }
 121         catch (ClassNotFoundException e1) {
 122             if (doFallback) {
 123                 // Use current class loader - should always be bootstrap CL
 124                 return Class.forName(className, false, FactoryFinder.class.getClassLoader());
 125             }
 126             else {
 127                 throw e1;
 128             }
 129         }
 130     }
 131 
 132     /**
 133      * Create an instance of a class. Delegates to method
 134      * <code>getProviderClass()</code> in order to load the class.
 135      *
 136      * @param type Base class / Service interface  of the factory to
 137      *             instantiate.
 138      *
 139      * @param className Name of the concrete class corresponding to the
 140      * service provider
 141      *
 142      * @param cl <code>ClassLoader</code> used to load the factory class. If <code>null</code>
 143      * current <code>Thread</code>'s context classLoader is used to load the factory class.
 144      *
 145      * @param doFallback True if the current ClassLoader should be tried as
 146      * a fallback if the class is not found using cl
 147      */
 148     static <T> T newInstance(Class<T> type, String className, ClassLoader cl,
 149                              boolean doFallback)
 150         throws FactoryConfigurationError
 151     {
 152         return newInstance(type, className, cl, doFallback, false);
 153     }
 154 
 155     /**
 156      * Create an instance of a class. Delegates to method
 157      * <code>getProviderClass()</code> in order to load the class.
 158      *
 159      * @param type Base class / Service interface  of the factory to
 160      *             instantiate.
 161      *
 162      * @param className Name of the concrete class corresponding to the
 163      * service provider
 164      *
 165      * @param cl <code>ClassLoader</code> used to load the factory class. If <code>null</code>
 166      * current <code>Thread</code>'s context classLoader is used to load the factory class.
 167      *
 168      * @param doFallback True if the current ClassLoader should be tried as
 169      * a fallback if the class is not found using cl
 170      *
 171      * @param useBSClsLoader True if cl=null actually meant bootstrap classLoader. This parameter
 172      * is needed since DocumentBuilderFactory/SAXParserFactory defined null as context classLoader.
 173      */
 174     static <T> T newInstance(Class<T> type, String className, ClassLoader cl,
 175                              boolean doFallback, boolean useBSClsLoader)
 176         throws FactoryConfigurationError
 177     {
 178         assert type != null;
 179         try {
 180             Class<?> providerClass = getProviderClass(className, cl, doFallback, useBSClsLoader);
 181             if (!type.isAssignableFrom(providerClass)) {
 182                 throw new ClassCastException(className + " cannot be cast to " + type.getName());
 183             }
 184             Object instance = providerClass.newInstance();
 185             if (debug) {    // Extra check to avoid computing cl strings
 186                 dPrint("created new instance of " + providerClass +
 187                        " using ClassLoader: " + cl);
 188             }
 189             return type.cast(instance);
 190         }
 191         catch (ClassNotFoundException x) {
 192             throw new FactoryConfigurationError(x,
 193                 "Provider " + className + " not found");
 194         }
 195         catch (Exception x) {
 196             throw new FactoryConfigurationError(x,
 197                 "Provider " + className + " could not be instantiated: " + x);
 198         }
 199     }
 200 
 201     /**
 202      * Finds the implementation Class object in the specified order.  Main
 203      * entry point.
 204      * @return Class object of factory, never null
 205      *
 206      * @param type                  Base class / Service interface  of the
 207      *                              factory to find.
 208      * @param fallbackClassName     Implementation class name, if nothing else
 209      *                              is found.  Use null to mean no fallback.
 210      *
 211      * Package private so this code can be shared.
 212      */
 213     static <T> T find(Class<T> type, String fallbackClassName)
 214         throws FactoryConfigurationError
 215     {
 216         final String factoryId = type.getName();
 217         dPrint("find factoryId =" + factoryId);
 218 
 219         // Use the system property first
 220         try {
 221             String systemProp = ss.getSystemProperty(factoryId);
 222             if (systemProp != null) {
 223                 dPrint("found system property, value=" + systemProp);
 224                 return newInstance(type, systemProp, null, true);
 225             }
 226         }
 227         catch (SecurityException se) {
 228             if (debug) se.printStackTrace();
 229         }
 230 
 231         // try to read from $java.home/lib/jaxp.properties
 232         try {
 233             String factoryClassName;
 234             if (firstTime) {
 235                 synchronized (cacheProps) {
 236                     if (firstTime) {
 237                         String configFile = ss.getSystemProperty("java.home") + File.separator +
 238                             "lib" + File.separator + "jaxp.properties";
 239                         File f = new File(configFile);
 240                         firstTime = false;
 241                         if (ss.doesFileExist(f)) {
 242                             dPrint("Read properties file "+f);
 243                             cacheProps.load(ss.getFileInputStream(f));
 244                         }
 245                     }
 246                 }
 247             }
 248             factoryClassName = cacheProps.getProperty(factoryId);
 249 
 250             if (factoryClassName != null) {
 251                 dPrint("found in $java.home/jaxp.properties, value=" + factoryClassName);
 252                 return newInstance(type, factoryClassName, null, true);
 253             }
 254         }
 255         catch (Exception ex) {
 256             if (debug) ex.printStackTrace();
 257         }
 258 
 259         // Try Jar Service Provider Mechanism
 260         T provider = findServiceProvider(type);
 261         if (provider != null) {
 262             return provider;
 263         }
 264         if (fallbackClassName == null) {
 265             throw new FactoryConfigurationError(
 266                 "Provider for " + factoryId + " cannot be found");
 267         }
 268 
 269         dPrint("loaded from fallback value: " + fallbackClassName);
 270         return newInstance(type, fallbackClassName, null, true);
 271     }
 272 
 273     /*
 274      * Try to find provider using the ServiceLoader API
 275      *
 276      * @param type Base class / Service interface  of the factory to find.
 277      *
 278      * @return instance of provider class if found or null
 279      */
 280     private static <T> T findServiceProvider(final Class<T> type) {
 281         try {
 282             return AccessController.doPrivileged(new PrivilegedAction<T>() {
 283                 public T run() {
 284                     final ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
 285                     final Iterator<T> iterator = serviceLoader.iterator();
 286                     if (iterator.hasNext()) {
 287                         return iterator.next();
 288                     } else {
 289                         return null;
 290                     }
 291                  }
 292             });
 293         } catch(ServiceConfigurationError e) {
 294             // It is not possible to wrap an error directly in
 295             // FactoryConfigurationError - so we need to wrap the
 296             // ServiceConfigurationError in a RuntimeException.
 297             // The alternative would be to modify the logic in
 298             // FactoryConfigurationError to allow setting a
 299             // Throwable as the cause, but that could cause
 300             // compatibility issues down the road.
 301             final RuntimeException x = new RuntimeException(
 302                     "Provider for " + type + " cannot be created", e);
 303             final FactoryConfigurationError error =
 304                     new FactoryConfigurationError(x, x.getMessage());
 305             throw error;
 306         }
 307     }
 308 
 309 }