1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package de.bea.domingo.map;
24
25 import java.util.HashMap;
26 import java.util.Map;
27
28 /***
29 * Factory for mapper objects.
30 *
31 * @see de.bea.domingo.map.DMapper
32 * @author <a href="mailto:kriede@users.sourceforge.net">Kurt Riede</a>
33 */
34 public final class MapperFactory {
35
36 /*** Maps instance classes to their mappers. */
37 private Map instanceMappers = new HashMap();
38
39 /*** Maps digest classes to their mappers. */
40 private Map digestMappers = new HashMap();
41
42 /***
43 * Creates and returns a new instance of this mapper factory.
44 *
45 * @return a new instance of this class
46 */
47 public static MapperFactory newInstance() {
48 return new MapperFactory();
49 }
50
51 /***
52 * private Constructor; use {@link #newInstance()} to get an instance of
53 * this class.
54 */
55 private MapperFactory() {
56 }
57
58 /***
59 * Registers a new mapper.
60 *
61 * @param mapperClass the class of the new mapper
62 * @throws MapperRegistrationException if the mapper cannot get registered
63 */
64 protected void registerMapper(final Class mapperClass) throws MapperRegistrationException {
65 if (mapperClass == null) {
66 throw new MapperRegistrationException("mapper class is null");
67 }
68 DMapper mapper = null;
69 try {
70 mapper = (DMapper) mapperClass.newInstance();
71 } catch (Exception e) {
72 throw new MapperRegistrationException("Cannot instantiate mapper of class " + mapperClass.getName(), e);
73 }
74 instanceMappers.put(mapper.getInstanceClass(), mapper);
75 digestMappers.put(mapper.getDigestClass(), mapper);
76 }
77
78 /***
79 * Returns the mapper that is registered for a given instance class.
80 *
81 * @param clazz the instance class
82 * @return mapper for that class
83 */
84 public DMapper getInstanceMapper(final Class clazz) {
85 DMapper mapper = (DMapper) instanceMappers.get(clazz);
86 if (mapper == null) {
87 Class[] interfaces = clazz.getInterfaces();
88 for (int i = 0; mapper == null && i < interfaces.length; i++) {
89 mapper = (DMapper) instanceMappers.get(interfaces[i]);
90 }
91 }
92 return mapper;
93 }
94
95 /***
96 * Returns the mapper that is registered for a given digest class.
97 *
98 * @param clazz the instance class
99 * @return mapper for that class
100 */
101 public DMapper getDigestMapper(final Class clazz) {
102 return (DMapper) digestMappers.get(clazz);
103 }
104 }