/* * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.xml.validation; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Properties; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; /** * Implementation of {@link SchemaFactory#newInstance(String)}. * * @author Kohsuke Kawaguchi * @version $Revision: 1.8 $, $Date: 2010-11-01 04:36:13 $ * @since 1.5 */ class SchemaFactoryFinder { private static final String DEFAULT_IMPL_NAME = "com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory"; /** * debug support code. */ private static boolean debug = false; /** *

Take care of restrictions imposed by java security model

*/ private static SecuritySupport ss = new SecuritySupport(); /** *

Cache properties for performance.

*/ private static Properties cacheProps = new Properties(); /** *

First time requires initialization overhead.

*/ private static volatile boolean firstTime = true; static { // Use try/catch block to support applets try { debug = ss.getSystemProperty("jaxp.debug") != null; } catch (Exception _) { debug = false; } } /** *

Conditional debug printing.

* * @param msg to print */ private static void debugPrintln(String msg) { if (debug) { System.err.println("JAXP: " + msg); } } /** *

ClassLoader to use to find * SchemaFactory.

*/ private final ClassLoader classLoader; /** *

Constructor that specifies * ClassLoader to use to find * SchemaFactory.

* * @param loader to be used to load resource, {@link SchemaFactory}, and * {@link SchemaFactoryLoader} implementations during the resolution * process. If this parameter is null, the default system class loader will * be used. */ public SchemaFactoryFinder(ClassLoader loader) { this.classLoader = loader; if (debug) { debugDisplayClassLoader(); } } private void debugDisplayClassLoader() { try { if (classLoader == ss.getContextClassLoader()) { debugPrintln("using thread context class loader (" + classLoader + ") for search"); return; } } catch (Throwable _) { ; // getContextClassLoader() undefined in JDK1.1 } if (classLoader == ClassLoader.getSystemClassLoader()) { debugPrintln("using system class loader (" + classLoader + ") for search"); return; } debugPrintln("using class loader (" + classLoader + ") for search"); } /** *

Creates a new {@link SchemaFactory} object for the specified schema * language.

* * @param schemaLanguage See {@link SchemaFactory Schema Language} table * in SchemaFactory for the list of available schema languages. * * @return null if the callee fails to create one. * * @throws NullPointerException If the schemaLanguage parameter * is null. */ public SchemaFactory newFactory(String schemaLanguage) throws FactoryConfigurationError { if (schemaLanguage == null) { throw new NullPointerException(); } SchemaFactory f = _newFactory(schemaLanguage); if (f != null) { debugPrintln("factory '" + f.getClass().getName() + "' was found for " + schemaLanguage); } else { debugPrintln("unable to find a factory for " + schemaLanguage); } return f; } /** *

Lookup a * SchemaFactory for the given * schemaLanguage.

* * @param schemaLanguage Schema language to * lookup SchemaFactory for. * * @return SchemaFactory for the * given schemaLanguage. */ private SchemaFactory _newFactory(String schemaLanguage) throws FactoryConfigurationError { SchemaFactory sf; String propertyName = SERVICE_CLASS.getName() + ":" + schemaLanguage; // system property look up try { debugPrintln("Looking up system property '" + propertyName + "'"); String r = ss.getSystemProperty(propertyName); if (r != null) { debugPrintln("The value is '" + r + "'"); sf = createInstance(r, true); if (sf != null) { return sf; } } else { debugPrintln("The property is undefined."); } } catch (Throwable t) { if (debug) { debugPrintln("failed to look up system property '" + propertyName + "'"); t.printStackTrace(); } } String javah = ss.getSystemProperty("java.home"); String configFile = javah + File.separator + "lib" + File.separator + "jaxp.properties"; String factoryClassName = null; // try to read from $java.home/lib/jaxp.properties try { if (firstTime) { synchronized (cacheProps) { if (firstTime) { File f = new File(configFile); firstTime = false; if (ss.doesFileExist(f)) { debugPrintln("Read properties file " + f); cacheProps.load(ss.getFileInputStream(f)); } } } } factoryClassName = cacheProps.getProperty(propertyName); debugPrintln("found " + factoryClassName + " in $java.home/jaxp.properties"); if (factoryClassName != null) { sf = createInstance(factoryClassName, true); if (sf != null) { return sf; } } } catch (Exception ex) { if (debug) { ex.printStackTrace(); } } // try finding a service provider sf = findServiceProvider(schemaLanguage, DEFAULT_IMPL_NAME); if (sf != null) { return sf; } // platform default if (schemaLanguage.equals("http://www.w3.org/2001/XMLSchema")) { debugPrintln("attempting to use the platform default XML Schema validator"); return createInstance(DEFAULT_IMPL_NAME, true); } debugPrintln("all things were tried, but none was found. bailing out."); return null; } /** *

Create class using appropriate ClassLoader.

* * @param className Name of class to create. * @return Created class or null. */ private Class createClass(String className) { Class clazz; // use approprite ClassLoader try { if (classLoader != null) { clazz = classLoader.loadClass(className); } else { clazz = Class.forName(className); } } catch (Throwable t) { if (debug) { t.printStackTrace(); } return null; } return clazz; } /** *

Creates an instance of the specified and returns it.

* * @param className fully qualified class name to be instanciated. * * @return null if it fails. Error messages will be printed by this method. */ SchemaFactory createInstance(String className) { return createInstance(className, false); } SchemaFactory createInstance(String className, boolean useServicesMechanism) { SchemaFactory schemaFactory = null; debugPrintln("createInstance(" + className + ")"); // get Class from className Class clazz = createClass(className); if (clazz == null) { debugPrintln("failed to getClass(" + className + ")"); return null; } debugPrintln("loaded " + className + " from " + which(clazz)); // instantiate Class as a SchemaFactory try { if (!useServicesMechanism) { schemaFactory = (SchemaFactory) newInstanceNoServiceLoader(clazz); } if (schemaFactory == null) { schemaFactory = (SchemaFactory) clazz.newInstance(); } } catch (ClassCastException classCastException) { debugPrintln("could not instantiate " + clazz.getName()); if (debug) { classCastException.printStackTrace(); } return null; } catch (IllegalAccessException illegalAccessException) { debugPrintln("could not instantiate " + clazz.getName()); if (debug) { illegalAccessException.printStackTrace(); } return null; } catch (InstantiationException instantiationException) { debugPrintln("could not instantiate " + clazz.getName()); if (debug) { instantiationException.printStackTrace(); } return null; } return schemaFactory; } /** * Try to construct using newTransformerFactoryNoServiceLoader method if * available. */ private static Object newInstanceNoServiceLoader( Class providerClass) { // Retain maximum compatibility if no security manager. if (System.getSecurityManager() == null) { return null; } try { Method creationMethod = providerClass.getDeclaredMethod( "newXMLSchemaFactoryNoServiceLoader"); return creationMethod.invoke(null, null); } catch (NoSuchMethodException exc) { return null; } catch (Exception exc) { return null; } } /* * Try to find a provider using Service Loader * * @return instance of provider class if found or null */ private SchemaFactory findServiceProvider(final String schemaLanguage, final String fallbackClassName) throws FactoryConfigurationError { try { return (SchemaFactory) AccessController.doPrivileged(new PrivilegedAction() { public SchemaFactory run() { SchemaFactory defaultProvider = null; for (SchemaFactory schemaFactory : ServiceLoader.load(SchemaFactory.class, classLoader)) { if (schemaFactory.getClass().getName().equals(fallbackClassName)) { defaultProvider = schemaFactory; } else { if (isSchemaSupported(schemaFactory, schemaLanguage)) { return schemaFactory; } } } if (defaultProvider != null) { return defaultProvider; } return null; } }); } catch (ServiceConfigurationError e) { throw new FactoryConfigurationError(e.getMessage(), (Exception) e.getCause()); } } /** *

Test if the specified schemas are supported by the provider.

* * @param schemaFactory a Schema factory provider. * @param schemaLanguage Schema Language to support. * * @return true if the Schema Language is supported by the * provider. */ private static boolean isSchemaSupported(SchemaFactory schemaFactory, String schemaLanguage) { final Class[] stringClassArray = {"".getClass()}; final Object[] schemaLanguageObjectArray = {schemaLanguage}; final String isSchemaLanguageSupportedMethod = "isSchemaLanguageSupported"; // does this Class support desired Schema? try { Method isSchemaLanguageSupported = schemaFactory.getClass().getMethod(isSchemaLanguageSupportedMethod, stringClassArray); Boolean supported = (Boolean) isSchemaLanguageSupported.invoke(schemaFactory, schemaLanguageObjectArray); if (supported.booleanValue()) { return true; } } catch (NoSuchMethodException noSuchMethodException) { } catch (IllegalAccessException illegalAccessException) { } catch (InvocationTargetException invocationTargetException) { } return false; } private static final Class SERVICE_CLASS = SchemaFactory.class; private static String which(Class clazz) { return which(clazz.getName(), clazz.getClassLoader()); } /** *

Search the specified classloader for the given classname.

* * @param classname the fully qualified name of the class to search for * @param loader the classloader to search * * @return the source location of the resource, or null if it wasn't found */ private static String which(String classname, ClassLoader loader) { String classnameAsResource = classname.replace('.', '/') + ".class"; if (loader == null) { loader = ClassLoader.getSystemClassLoader(); } //URL it = loader.getResource(classnameAsResource); URL it = ss.getResourceAsURL(loader, classnameAsResource); if (it != null) { return it.toString(); } else { return null; } } }