1 18 package org.apache.activemq.util; 19 20 import java.io.BufferedInputStream ; 21 import java.io.IOException ; 22 import java.io.InputStream ; 23 import java.util.Properties ; 24 25 import java.util.concurrent.ConcurrentHashMap ; 26 27 28 public class FactoryFinder { 29 30 private final String path; 31 private final ConcurrentHashMap classMap = new ConcurrentHashMap (); 32 33 public FactoryFinder(String path) { 34 this.path = path; 35 } 36 37 44 public Object newInstance(String key) 45 throws IllegalAccessException , InstantiationException , IOException , ClassNotFoundException 46 { 47 return newInstance(key, null); 48 } 49 50 public Object newInstance(String key, String propertyPrefix) 51 throws IllegalAccessException , InstantiationException , IOException , ClassNotFoundException 52 { 53 if (propertyPrefix == null) 54 propertyPrefix = ""; 55 56 Class clazz = (Class ) classMap.get(propertyPrefix + key); 57 if (clazz == null) { 58 clazz = newInstance(doFindFactoryProperies(key), propertyPrefix); 59 classMap.put(propertyPrefix + key, clazz); 60 } 61 return clazz.newInstance(); 62 } 63 64 private Class newInstance(Properties properties, String propertyPrefix) throws ClassNotFoundException , IOException { 65 66 String className = properties.getProperty(propertyPrefix + "class"); 67 if (className == null) { 68 throw new IOException ("Expected property is missing: " + propertyPrefix + "class"); 69 } 70 Class clazz; 71 try { 72 clazz = Thread.currentThread().getContextClassLoader().loadClass(className); 73 } catch (ClassNotFoundException e) { 74 clazz = FactoryFinder.class.getClassLoader().loadClass(className); 75 } 76 77 return clazz; 78 } 79 80 private Properties doFindFactoryProperies(String key) throws IOException { 81 String uri = path + key; 82 83 ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 85 if (classLoader == null) classLoader = getClass().getClassLoader(); 86 InputStream in = classLoader.getResourceAsStream(uri); 87 if (in == null) { 88 in = FactoryFinder.class.getClassLoader().getResourceAsStream(uri); 89 if (in == null) { 90 throw new IOException ("Could not find factory class for resource: " + uri); 91 } 92 } 93 94 BufferedInputStream reader = null; 96 try { 97 reader = new BufferedInputStream (in); 98 Properties properties = new Properties (); 99 properties.load(reader); 100 return properties; 101 } finally { 102 try { 103 reader.close(); 104 } catch (Exception e) { 105 } 106 } 107 } 108 } 109 | Popular Tags |