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