1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 // $Id: SchemaFactoryFinder.java 727367 2008-12-17 13:05:26Z mrglavas $ 18 19 package javax.xml.validation; 20 21 import java.io.BufferedReader; 22 import java.io.File; 23 import java.io.IOException; 24 import java.io.InputStream; 25 import java.io.InputStreamReader; 26 import java.net.URL; 27 import java.util.ArrayList; 28 import java.util.Enumeration; 29 import java.util.Iterator; 30 import java.util.NoSuchElementException; 31 import java.util.Properties; 32 import javax.xml.XMLConstants; 33 34 /** 35 * Implementation of {@link SchemaFactory#newInstance(String)}. 36 * 37 * @author <a href="Kohsuke.Kawaguchi (at) Sun.com">Kohsuke Kawaguchi</a> 38 * @version $Revision: 727367 $, $Date: 2008-12-17 05:05:26 -0800 (Wed, 17 Dec 2008) $ 39 * @since 1.5 40 */ 41 final class SchemaFactoryFinder { 42 43 /** XML Schema language identifiers. */ 44 private static final String W3C_XML_SCHEMA10_NS_URI = "http://www.w3.org/XML/XMLSchema/v1.0"; 45 private static final String W3C_XML_SCHEMA11_NS_URI = "http://www.w3.org/XML/XMLSchema/v1.1"; 46 47 /** debug support code. */ 48 private static boolean debug = false; 49 50 /** 51 * <p>Cache properties for performance.</p> 52 */ 53 private static Properties cacheProps = new Properties(); 54 55 /** 56 * <p>First time requires initialization overhead.</p> 57 */ 58 private static boolean firstTime = true; 59 60 /** 61 * Default columns per line. 62 */ 63 private static final int DEFAULT_LINE_LENGTH = 80; 64 65 static { 66 // Use try/catch block to support applets 67 try { 68 String val = SecuritySupport.getSystemProperty("jaxp.debug"); 69 // Allow simply setting the prop to turn on debug 70 debug = val != null && (! "false".equals(val)); 71 } catch (Exception _) { 72 debug = false; 73 } 74 } 75 76 /** 77 * <p>Conditional debug printing.</p> 78 * 79 * @param msg to print 80 */ 81 private static void debugPrintln(String msg) { 82 if (debug) { 83 System.err.println("JAXP: " + msg); 84 } 85 } 86 87 /** 88 * <p><code>ClassLoader</code> to use to find <code>SchemaFactory</code>.</p> 89 */ 90 private final ClassLoader classLoader; 91 92 /** 93 * <p>Constructor that specifies <code>ClassLoader</code> to use 94 * to find <code>SchemaFactory</code>.</p> 95 * 96 * @param loader 97 * to be used to load resource, {@link SchemaFactory}, and 98 * {@link SchemaFactoryLoader} implementations during 99 * the resolution process. 100 * If this parameter is null, the default system class loader 101 * will be used. 102 */ 103 public SchemaFactoryFinder(ClassLoader loader) { 104 this.classLoader = loader; 105 if( debug ) { 106 debugDisplayClassLoader(); 107 } 108 } 109 110 private void debugDisplayClassLoader() { 111 try { 112 if( classLoader == SecuritySupport.getContextClassLoader() ) { 113 debugPrintln("using thread context class loader ("+classLoader+") for search"); 114 return; 115 } 116 } 117 // The VM ran out of memory or there was some other serious problem. Re-throw. 118 catch (VirtualMachineError vme) { 119 throw vme; 120 } 121 // ThreadDeath should always be re-thrown 122 catch (ThreadDeath td) { 123 throw td; 124 } 125 catch (Throwable _) { 126 ; // getContextClassLoader() undefined in JDK1.1 127 } 128 129 if( classLoader==ClassLoader.getSystemClassLoader() ) { 130 debugPrintln("using system class loader ("+classLoader+") for search"); 131 return; 132 } 133 134 debugPrintln("using class loader ("+classLoader+") for search"); 135 } 136 137 /** 138 * <p>Creates a new {@link SchemaFactory} object for the specified 139 * schema language.</p> 140 * 141 * @param schemaLanguage 142 * See {@link SchemaFactory Schema Language} table in <code>SchemaFactory</code> 143 * for the list of available schema languages. 144 * 145 * @return <code>null</code> if the callee fails to create one. 146 * 147 * @throws NullPointerException 148 * If the <tt>schemaLanguage</tt> parameter is null. 149 */ 150 public SchemaFactory newFactory(String schemaLanguage) { 151 if(schemaLanguage==null) throw new NullPointerException(); 152 SchemaFactory f = _newFactory(schemaLanguage); 153 if (debug) { 154 if (f != null) { 155 debugPrintln("factory '" + f.getClass().getName() + "' was found for " + schemaLanguage); 156 } else { 157 debugPrintln("unable to find a factory for " + schemaLanguage); 158 } 159 } 160 return f; 161 } 162 163 /** 164 * <p>Lookup a <code>SchemaFactory</code> for the given <code>schemaLanguage</code>.</p> 165 * 166 * @param schemaLanguage Schema language to lookup <code>SchemaFactory</code> for. 167 * 168 * @return <code>SchemaFactory</code> for the given <code>schemaLanguage</code>. 169 */ 170 private SchemaFactory _newFactory(String schemaLanguage) { 171 SchemaFactory sf; 172 String propertyName = SERVICE_CLASS.getName() + ":" + schemaLanguage; 173 174 // system property look up 175 try { 176 if (debug) debugPrintln("Looking up system property '"+propertyName+"'" ); 177 String r = SecuritySupport.getSystemProperty(propertyName); 178 if (r != null && r.length() > 0) { 179 if (debug) debugPrintln("The value is '"+r+"'"); 180 sf = createInstance(r); 181 if(sf!=null) return sf; 182 } 183 else if (debug) { 184 debugPrintln("The property is undefined."); 185 } 186 } 187 // The VM ran out of memory or there was some other serious problem. Re-throw. 188 catch (VirtualMachineError vme) { 189 throw vme; 190 } 191 // ThreadDeath should always be re-thrown 192 catch (ThreadDeath td) { 193 throw td; 194 } 195 catch (Throwable t) { 196 if( debug ) { 197 debugPrintln("failed to look up system property '"+propertyName+"'" ); 198 t.printStackTrace(); 199 } 200 } 201 202 String javah = SecuritySupport.getSystemProperty( "java.home" ); 203 String configFile = javah + File.separator + 204 "lib" + File.separator + "jaxp.properties"; 205 206 String factoryClassName = null ; 207 208 // try to read from $java.home/lib/jaxp.properties 209 try { 210 if(firstTime){ 211 synchronized(cacheProps){ 212 if(firstTime){ 213 File f=new File( configFile ); 214 firstTime = false; 215 if(SecuritySupport.doesFileExist(f)){ 216 if (debug) debugPrintln("Read properties file " + f); 217 cacheProps.load(SecuritySupport.getFileInputStream(f)); 218 } 219 } 220 } 221 } 222 factoryClassName = cacheProps.getProperty(propertyName); 223 if (debug) debugPrintln("found " + factoryClassName + " in $java.home/jaxp.properties"); 224 225 if (factoryClassName != null) { 226 sf = createInstance(factoryClassName); 227 if(sf != null){ 228 return sf; 229 } 230 } 231 } catch (Exception ex) { 232 if (debug) { 233 ex.printStackTrace(); 234 } 235 } 236 237 /** 238 // try to read from $java.home/lib/jaxp.properties 239 try { 240 String javah = ss.getSystemProperty( "java.home" ); 241 String configFile = javah + File.separator + 242 "lib" + File.separator + "jaxp.properties"; 243 File f = new File( configFile ); 244 if( ss.doesFileExist(f)) { 245 sf = loadFromProperty( 246 propertyName,f.getAbsolutePath(), new FileInputStream(f)); 247 if(sf!=null) return sf; 248 } else { 249 debugPrintln("Tried to read "+ f.getAbsolutePath()+", but it doesn't exist."); 250 } 251 } catch(Throwable e) { 252 if( debug ) { 253 debugPrintln("failed to read $java.home/lib/jaxp.properties"); 254 e.printStackTrace(); 255 } 256 } 257 */ 258 259 // try META-INF/services files 260 Iterator sitr = createServiceFileIterator(); 261 while(sitr.hasNext()) { 262 URL resource = (URL)sitr.next(); 263 if (debug) debugPrintln("looking into " + resource); 264 try { 265 sf = loadFromServicesFile(schemaLanguage,resource.toExternalForm(),SecuritySupport.getURLInputStream(resource)); 266 if(sf!=null) return sf; 267 } catch(IOException e) { 268 if( debug ) { 269 debugPrintln("failed to read "+resource); 270 e.printStackTrace(); 271 } 272 } 273 } 274 275 // platform defaults 276 if (schemaLanguage.equals(XMLConstants.W3C_XML_SCHEMA_NS_URI) || schemaLanguage.equals(W3C_XML_SCHEMA10_NS_URI)) { 277 if (debug) debugPrintln("attempting to use the platform default XML Schema 1.0 validator"); 278 return createInstance("org.apache.xerces.jaxp.validation.XMLSchemaFactory"); 279 } 280 else if (schemaLanguage.equals(W3C_XML_SCHEMA11_NS_URI)) { 281 if (debug) debugPrintln("attempting to use the platform default XML Schema 1.1 validator"); 282 return createInstance("org.apache.xerces.jaxp.validation.XMLSchema11Factory"); 283 } 284 285 if (debug) debugPrintln("all things were tried, but none was found. bailing out."); 286 return null; 287 } 288 289 /** 290 * <p>Creates an instance of the specified and returns it.</p> 291 * 292 * @param className 293 * fully qualified class name to be instantiated. 294 * 295 * @return null 296 * if it fails. Error messages will be printed by this method. 297 */ 298 SchemaFactory createInstance( String className ) { 299 try { 300 if (debug) debugPrintln("instanciating "+className); 301 Class clazz; 302 if( classLoader!=null ) 303 clazz = classLoader.loadClass(className); 304 else 305 clazz = Class.forName(className); 306 if(debug) debugPrintln("loaded it from "+which(clazz)); 307 Object o = clazz.newInstance(); 308 309 if( o instanceof SchemaFactory ) 310 return (SchemaFactory)o; 311 312 if (debug) debugPrintln(className+" is not assignable to "+SERVICE_CLASS.getName()); 313 } 314 // The VM ran out of memory or there was some other serious problem. Re-throw. 315 catch (VirtualMachineError vme) { 316 throw vme; 317 } 318 // ThreadDeath should always be re-thrown 319 catch (ThreadDeath td) { 320 throw td; 321 } 322 catch (Throwable t) { 323 debugPrintln("failed to instanciate "+className); 324 if(debug) t.printStackTrace(); 325 } 326 return null; 327 } 328 329 /** Iterator that lazily computes one value and returns it. */ 330 private static abstract class SingleIterator implements Iterator { 331 private boolean seen = false; 332 333 public final void remove() { throw new UnsupportedOperationException(); } 334 public final boolean hasNext() { return !seen; } 335 public final Object next() { 336 if(seen) throw new NoSuchElementException(); 337 seen = true; 338 return value(); 339 } 340 341 protected abstract Object value(); 342 } 343 344 /** 345 * Returns an {@link Iterator} that enumerates all 346 * the META-INF/services files that we care. 347 */ 348 private Iterator createServiceFileIterator() { 349 if (classLoader == null) { 350 return new SingleIterator() { 351 protected Object value() { 352 ClassLoader classLoader = SchemaFactoryFinder.class.getClassLoader(); 353 //return (ClassLoader.getSystemResource( SERVICE_ID )); 354 return SecuritySupport.getResourceAsURL(classLoader, SERVICE_ID); 355 } 356 }; 357 } else { 358 try { 359 //final Enumeration e = classLoader.getResources(SERVICE_ID); 360 final Enumeration e = SecuritySupport.getResources(classLoader, SERVICE_ID); 361 if(debug && !e.hasMoreElements()) { 362 debugPrintln("no "+SERVICE_ID+" file was found"); 363 } 364 365 // wrap it into an Iterator. 366 return new Iterator() { 367 public void remove() { 368 throw new UnsupportedOperationException(); 369 } 370 371 public boolean hasNext() { 372 return e.hasMoreElements(); 373 } 374 375 public Object next() { 376 return e.nextElement(); 377 } 378 }; 379 } catch (IOException e) { 380 if (debug) { 381 debugPrintln("failed to enumerate resources "+SERVICE_ID); 382 e.printStackTrace(); 383 } 384 return new ArrayList().iterator(); // empty iterator 385 } 386 } 387 } 388 389 /** Searches for a SchemaFactory for a given schema language in a META-INF/services file. */ 390 private SchemaFactory loadFromServicesFile(String schemaLanguage, String resourceName, InputStream in) { 391 392 if (debug) debugPrintln("Reading "+resourceName ); 393 394 // Read the service provider name in UTF-8 as specified in 395 // the jar spec. Unfortunately this fails in Microsoft 396 // VJ++, which does not implement the UTF-8 397 // encoding. Theoretically, we should simply let it fail in 398 // that case, since the JVM is obviously broken if it 399 // doesn't support such a basic standard. But since there 400 // are still some users attempting to use VJ++ for 401 // development, we have dropped in a fallback which makes a 402 // second attempt using the platform's default encoding. In 403 // VJ++ this is apparently ASCII, which is a subset of 404 // UTF-8... and since the strings we'll be reading here are 405 // also primarily limited to the 7-bit ASCII range (at 406 // least, in English versions), this should work well 407 // enough to keep us on the air until we're ready to 408 // officially decommit from VJ++. [Edited comment from 409 // jkesselm] 410 BufferedReader rd; 411 try { 412 rd = new BufferedReader(new InputStreamReader(in, "UTF-8"), DEFAULT_LINE_LENGTH); 413 } catch (java.io.UnsupportedEncodingException e) { 414 rd = new BufferedReader(new InputStreamReader(in), DEFAULT_LINE_LENGTH); 415 } 416 417 String factoryClassName = null; 418 SchemaFactory resultFactory = null; 419 // See spec for provider-configuration files: http://java.sun.com/j2se/1.5.0/docs/guide/jar/jar.html#Provider%20Configuration%20File 420 while (true) { 421 try { 422 factoryClassName = rd.readLine(); 423 } catch (IOException x) { 424 // No provider found 425 break; 426 } 427 if (factoryClassName != null) { 428 // Ignore comments in the provider-configuration file 429 int hashIndex = factoryClassName.indexOf('#'); 430 if (hashIndex != -1) { 431 factoryClassName = factoryClassName.substring(0, hashIndex); 432 } 433 434 // Ignore leading and trailing whitespace 435 factoryClassName = factoryClassName.trim(); 436 437 // If there's no text left or if this was a blank line, go to the next one. 438 if (factoryClassName.length() == 0) { 439 continue; 440 } 441 442 try { 443 // Found the right SchemaFactory if its isSchemaLanguageSupported(schemaLanguage) method returns true. 444 SchemaFactory foundFactory = (SchemaFactory) createInstance(factoryClassName); 445 if (foundFactory.isSchemaLanguageSupported(schemaLanguage)) { 446 resultFactory = foundFactory; 447 break; 448 } 449 } 450 catch (Exception e) {} 451 } 452 else { 453 break; 454 } 455 } 456 457 try { 458 // try to close the reader. 459 rd.close(); 460 } 461 // Ignore the exception. 462 catch (IOException exc) {} 463 464 return resultFactory; 465 } 466 467 private static final Class SERVICE_CLASS = SchemaFactory.class; 468 private static final String SERVICE_ID = "META-INF/services/" + SERVICE_CLASS.getName(); 469 470 471 472 private static String which( Class clazz ) { 473 return which( clazz.getName(), clazz.getClassLoader() ); 474 } 475 476 /** 477 * <p>Search the specified classloader for the given classname.</p> 478 * 479 * @param classname the fully qualified name of the class to search for 480 * @param loader the classloader to search 481 * 482 * @return the source location of the resource, or null if it wasn't found 483 */ 484 private static String which(String classname, ClassLoader loader) { 485 486 String classnameAsResource = classname.replace('.', '/') + ".class"; 487 488 if( loader==null ) loader = ClassLoader.getSystemClassLoader(); 489 490 //URL it = loader.getResource(classnameAsResource); 491 URL it = SecuritySupport.getResourceAsURL(loader, classnameAsResource); 492 if (it != null) { 493 return it.toString(); 494 } else { 495 return null; 496 } 497 } 498 } 499