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