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