01: // This file is part of KeY - Integrated Deductive Software Design
02: // Copyright (C) 2001-2007 Universitaet Karlsruhe, Germany
03: // Universitaet Koblenz-Landau, Germany
04: // Chalmers University of Technology, Sweden
05: //
06: // The KeY system is protected by the GNU General Public License.
07: // See LICENSE.TXT for details.
08: //
09: //
10:
11: package de.uka.ilkd.key.util;
12:
13: import java.io.BufferedReader;
14: import java.io.IOException;
15: import java.io.InputStream;
16: import java.io.InputStreamReader;
17:
18: /**
19: * The Service class contains a static method to load a class and a
20: * create an instance specified by an identifier. The corresponding
21: * class can be specified by a system property or by a service entry
22: * in the META-INF directory.
23: */
24:
25: public final class Service {
26:
27: /** Search for a class with id and return a new instance. If no
28: * class is found, defaultClassName is used instead. */
29: public static final Object find(String id, String defaultClassName) {
30: // use the system property first
31: String systemProperty = System.getProperty(id);
32: if (systemProperty != null) {
33: return newInstance(systemProperty);
34: }
35:
36: // try to find services in classpath
37: String serviceId = "META-INF/services/" + id;
38: InputStream in = ClassLoader
39: .getSystemResourceAsStream(serviceId);
40: if (in != null) {
41: try {
42: BufferedReader rd = new BufferedReader(
43: new InputStreamReader(in, "UTF-8"));
44: String className = rd.readLine();
45: rd.close();
46: if (className != null && !"".equals(className)) {
47: return newInstance(className);
48: }
49: } catch (IOException ioe) {
50: throw new RuntimeException("Error: " + ioe);
51: }
52: }
53:
54: // fall back to default
55: return newInstance(defaultClassName);
56: }
57:
58: /** create and return a new instance of className. */
59: private static final Object newInstance(String className) {
60: try {
61: Class cl = Class.forName(className);
62: return cl.newInstance();
63: } catch (ClassNotFoundException cnfe) {
64: throw new RuntimeException("Service " + className
65: + " not found.");
66: } catch (Exception e) {
67: throw new RuntimeException("Service " + className
68: + " could not be instantiated: " + e);
69: }
70: }
71:
72: /** no instances of this class are required. */
73: private Service() {
74: }
75:
76: }
|