01: /*
02: * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.util.factory;
05:
06: import java.io.BufferedReader;
07: import java.io.IOException;
08: import java.io.InputStream;
09: import java.io.InputStreamReader;
10:
11: public abstract class AbstractFactory {
12: public static AbstractFactory getFactory(String id,
13: Class defaultImpl) {
14: String factoryClassName = findFactoryClassName(id);
15: AbstractFactory factory = null;
16:
17: if (factoryClassName != null) {
18: try {
19: factory = (AbstractFactory) Class.forName(
20: factoryClassName).newInstance();
21: } catch (Exception e) {
22: throw new RuntimeException("Could not instantiate '"
23: + factoryClassName + "'", e);
24: }
25: }
26:
27: if (factory == null) {
28: try {
29: factory = (AbstractFactory) defaultImpl.newInstance();
30: } catch (Exception e) {
31: throw new RuntimeException(e);
32: }
33: }
34:
35: return factory;
36: }
37:
38: private static String findFactoryClassName(String id) {
39: String serviceId = "META-INF/services/" + id;
40: InputStream is = null;
41:
42: ClassLoader cl = AbstractFactory.class.getClassLoader();
43: if (cl != null) {
44: is = cl.getResourceAsStream(serviceId);
45: }
46:
47: if (is == null) {
48: return System.getProperty(id);
49: }
50:
51: BufferedReader rd;
52: try {
53: rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
54: } catch (java.io.UnsupportedEncodingException e) {
55: rd = new BufferedReader(new InputStreamReader(is));
56: }
57:
58: String factoryClassName = null;
59: try {
60: factoryClassName = rd.readLine();
61: rd.close();
62: } catch (IOException x) {
63: return System.getProperty(id);
64: }
65:
66: if (factoryClassName != null && !"".equals(factoryClassName)) {
67: return factoryClassName;
68: }
69:
70: return System.getProperty(id);
71: }
72: }
|