1 4 package com.tc.util.factory; 5 6 import java.io.BufferedReader ; 7 import java.io.IOException ; 8 import java.io.InputStream ; 9 import java.io.InputStreamReader ; 10 11 public abstract class AbstractFactory { 12 public static AbstractFactory getFactory(String id, Class defaultImpl) { 13 String factoryClassName = findFactoryClassName(id); 14 AbstractFactory factory = null; 15 16 if(factoryClassName != null) { 17 try { 18 factory = (AbstractFactory)Class.forName(factoryClassName).newInstance(); 19 } catch(Exception e) { 20 throw new RuntimeException ("Could not instantiate '"+factoryClassName+"'", e); 21 } 22 } 23 24 if(factory == null) { 25 try { 26 factory = (AbstractFactory)defaultImpl.newInstance(); 27 } catch(Exception e) { 28 throw new RuntimeException (e); 29 } 30 } 31 32 return factory; 33 } 34 35 private static String findFactoryClassName(String id) { 36 String serviceId = "META-INF/services/"+id; 37 InputStream is = null; 38 39 ClassLoader cl = AbstractFactory.class.getClassLoader(); 40 if (cl != null) { 41 is = cl.getResourceAsStream(serviceId); 42 } 43 44 if (is == null) { 45 return System.getProperty(id); 46 } 47 48 BufferedReader rd; 49 try { 50 rd = new BufferedReader (new InputStreamReader (is, "UTF-8")); 51 } catch (java.io.UnsupportedEncodingException e) { 52 rd = new BufferedReader (new InputStreamReader (is)); 53 } 54 55 String factoryClassName = null; 56 try { 57 factoryClassName = rd.readLine(); 58 rd.close(); 59 } catch(IOException x) { 60 return System.getProperty(id); 61 } 62 63 if (factoryClassName != null && !"".equals(factoryClassName)) { 64 return factoryClassName; 65 } 66 67 return System.getProperty(id); 68 } 69 } 70 | Popular Tags |