01: package com.bm.creators;
02:
03: import java.util.HashMap;
04: import java.util.Map;
05: import java.util.Set;
06:
07: import javax.ejb.SessionContext;
08: import javax.ejb.TimerService;
09: import javax.persistence.EntityManager;
10: import javax.sql.DataSource;
11:
12: import com.bm.cfg.Ejb3UnitCfg;
13: import com.bm.ejb3guice.inject.Binder;
14: import com.bm.ejb3guice.inject.Module;
15: import com.bm.utils.BasicDataSource;
16: import com.bm.utils.substitues.FakedSessionContext;
17: import com.bm.utils.substitues.MockedTimerService;
18:
19: public class DynamicDIModuleCreator implements Module {
20:
21: private final Map<String, String> interface2implemantation;
22:
23: private final Ejb3UnitCfg conf;
24:
25: private final EntityManager manager;
26:
27: /**
28: * Constructor.
29: *
30: * @param manager
31: * the entity manager instance which should be used for the
32: * binding
33: */
34: public DynamicDIModuleCreator(Ejb3UnitCfg conf,
35: EntityManager manager) {
36: this .interface2implemantation = new HashMap<String, String>();
37: this .conf = conf;
38: this .manager = manager;
39: }
40:
41: /**
42: * Adds a map with interface impl. to the structure.
43: *
44: * @author Daniel Wiese
45: * @since Jul 19, 2007
46: * @param toAdd
47: * the map to add
48: */
49: public void addInteface2ImplMap(Map<String, String> toAdd) {
50: final Set<String> keySet = toAdd.keySet();
51: for (String interfaze : keySet) {
52: this .interface2implemantation.put(interfaze, toAdd
53: .get(interfaze));
54: }
55: }
56:
57: @SuppressWarnings("unchecked")
58: public void configure(Binder binder) {
59: // static standard bindings
60: binder.bind(DataSource.class).toInstance(
61: new BasicDataSource(this .conf));
62: binder.bind(EntityManager.class).toInstance(this .manager);
63: binder.bind(SessionContext.class).to(FakedSessionContext.class);
64: binder.bind(TimerService.class).to(MockedTimerService.class);
65:
66: for (String interfaze : interface2implemantation.keySet()) {
67: try {
68: Class<Object> interfazeCl = (Class<Object>) Thread
69: .currentThread().getContextClassLoader()
70: .loadClass(interfaze.replace('/', '.'));
71: Class<Object> implementationCl = (Class<Object>) Thread
72: .currentThread().getContextClassLoader()
73: .loadClass(
74: interface2implemantation.get(interfaze)
75: .replace('/', '.'));
76: binder.bind(interfazeCl).to(implementationCl);
77: } catch (ClassNotFoundException e) {
78: throw new RuntimeException(
79: "Can't load Local/Remote interface "
80: + interfaze);
81: }
82: }
83:
84: }
85: }
|