KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > factory > AbstractFactory


1 /*
2  * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util.factory;
5
6 import java.io.BufferedReader JavaDoc;
7 import java.io.IOException JavaDoc;
8 import java.io.InputStream JavaDoc;
9 import java.io.InputStreamReader JavaDoc;
10
11 public abstract class AbstractFactory {
12   public static AbstractFactory getFactory(String JavaDoc id, Class JavaDoc defaultImpl) {
13     String JavaDoc factoryClassName = findFactoryClassName(id);
14     AbstractFactory factory = null;
15     
16     if(factoryClassName != null) {
17       try {
18         factory = (AbstractFactory)Class.forName(factoryClassName).newInstance();
19       } catch(Exception JavaDoc e) {
20         throw new RuntimeException JavaDoc("Could not instantiate '"+factoryClassName+"'", e);
21       }
22     }
23     
24     if(factory == null) {
25       try {
26         factory = (AbstractFactory)defaultImpl.newInstance();
27       } catch(Exception JavaDoc e) {
28         throw new RuntimeException JavaDoc(e);
29       }
30     }
31
32     return factory;
33   }
34     
35     private static String JavaDoc findFactoryClassName(String JavaDoc id) {
36       String JavaDoc serviceId = "META-INF/services/"+id;
37       InputStream JavaDoc is = null;
38
39       ClassLoader JavaDoc 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 JavaDoc rd;
49       try {
50         rd = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is, "UTF-8"));
51       } catch (java.io.UnsupportedEncodingException JavaDoc e) {
52         rd = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
53       }
54       
55       String JavaDoc factoryClassName = null;
56       try {
57         factoryClassName = rd.readLine();
58         rd.close();
59       } catch(IOException JavaDoc 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