1 22 package javax.xml.stream; 23 24 import java.io.BufferedReader ; 25 import java.io.File ; 26 import java.io.FileInputStream ; 27 import java.io.InputStream ; 28 import java.io.InputStreamReader ; 29 import java.util.Properties ; 30 31 38 class FactoryLocator 39 { 40 41 private static final String JAVA_HOME = System.getProperty("java.home"); 42 43 private static final String PROPERTY_FILE = JAVA_HOME + File.pathSeparator + "lib" + File.pathSeparator + "xml.stream.properties"; 44 45 private static final String SERVICES_PATH = "META-INF/services/"; 46 47 private static Object newInstance(String className, ClassLoader classLoader) 48 { 49 try 50 { 51 return classLoader.loadClass(className).newInstance(); 52 } 53 catch (ClassNotFoundException e) 54 { 55 throw new FactoryConfigurationError("Could not locate provider [" + className + "]", e); 56 } 57 catch (Exception e) 58 { 59 throw new FactoryConfigurationError("Error creating provider [" + className + "]", e); 60 } 61 } 62 63 66 private static String getPropertyFromFile(String property) 67 { 68 File file = new File (PROPERTY_FILE); 69 70 if (!file.exists()) 71 return null; 72 73 Properties properties = new Properties (); 74 try 75 { 76 properties.load(new FileInputStream (file)); 77 return properties.getProperty(property); 78 } 79 catch (Exception e) 80 { 81 return null; 83 } 84 } 85 86 private static String getPropertyFromServices(String property, ClassLoader classLoader) 87 { 88 String resource = SERVICES_PATH + property; 89 InputStream stream = classLoader.getResourceAsStream(property); 90 91 if (stream == null) 92 return null; 93 try 94 { 95 BufferedReader reader = new BufferedReader (new InputStreamReader (stream, "UTF-8")); 96 return reader.readLine(); 97 } 98 catch (Exception e) 99 { 100 return null; 102 } 103 } 104 105 111 static Object find(String factoryId, String defaultFactory) throws FactoryConfigurationError 112 { 113 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 114 return find(factoryId, defaultFactory, loader); 115 } 116 117 128 static Object find(String factoryId, String defaultFactory, ClassLoader classLoader) throws FactoryConfigurationError 129 { 130 if (classLoader == null) 131 throw new FactoryConfigurationError("Could not determine classloader."); 132 133 String value = System.getProperty(factoryId); 134 if (value != null) 135 return newInstance(value, classLoader); 136 137 value = getPropertyFromFile(factoryId); 138 if (value != null) 139 return newInstance(value, classLoader); 140 141 value = getPropertyFromServices(factoryId, classLoader); 142 if (value != null) 143 return newInstance(value, classLoader); 144 145 return newInstance(defaultFactory, classLoader); 146 } 147 } 148 | Popular Tags |