01: // Copyright 2004, 2005 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.hivemind.lib.impl;
16:
17: import java.util.Collections;
18: import java.util.HashMap;
19: import java.util.Map;
20:
21: import org.apache.hivemind.ApplicationRuntimeException;
22: import org.apache.hivemind.impl.BaseLocatable;
23: import org.apache.hivemind.lib.DefaultImplementationBuilder;
24: import org.apache.hivemind.service.ClassFab;
25: import org.apache.hivemind.service.ClassFabUtils;
26: import org.apache.hivemind.service.ClassFactory;
27: import org.apache.hivemind.service.MethodIterator;
28:
29: /**
30: * Implemenation of {@link org.apache.hivemind.lib.DefaultImplementationBuilder}.
31: *
32: * @author Howard Lewis Ship
33: */
34: public class DefaultImplementationBuilderImpl extends BaseLocatable
35: implements DefaultImplementationBuilder {
36: private Map _instances = Collections.synchronizedMap(new HashMap());
37:
38: private ClassFactory _classFactory;
39:
40: public Object buildDefaultImplementation(Class interfaceType) {
41: Object result = _instances.get(interfaceType);
42:
43: if (result == null) {
44: result = create(interfaceType);
45:
46: _instances.put(interfaceType, result);
47: }
48:
49: return result;
50: }
51:
52: private Object create(Class interfaceType) {
53: Class defaultClass = createClass(interfaceType);
54:
55: try {
56: return defaultClass.newInstance();
57: } catch (Exception ex) {
58: throw new ApplicationRuntimeException(ImplMessages
59: .unableToCreateDefaultImplementation(interfaceType,
60: ex), ex);
61: }
62: }
63:
64: private Class createClass(Class interfaceType) {
65: if (!interfaceType.isInterface())
66: throw new ApplicationRuntimeException(ImplMessages
67: .notAnInterface(interfaceType));
68:
69: String name = ClassFabUtils.generateClassName(interfaceType);
70:
71: ClassFab cf = _classFactory.newClass(name, Object.class);
72:
73: cf.addInterface(interfaceType);
74:
75: MethodIterator mi = new MethodIterator(interfaceType);
76:
77: while (mi.hasNext()) {
78: ClassFabUtils.addNoOpMethod(cf, mi.next());
79: }
80:
81: if (!mi.getToString())
82: ClassFabUtils.addToStringMethod(cf, ImplMessages
83: .defaultImplementationDescription(interfaceType));
84:
85: return cf.createClass();
86: }
87:
88: public void setClassFactory(ClassFactory factory) {
89: _classFactory = factory;
90: }
91:
92: }
|