1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package net.sf.morph.transform.converters;
17
18 import java.util.Iterator;
19 import java.util.Locale;
20 import java.util.Map;
21
22 import net.sf.composite.util.ObjectUtils;
23 import net.sf.morph.transform.DecoratedConverter;
24 import net.sf.morph.transform.TransformationException;
25 import net.sf.morph.transform.transformers.BaseTransformer;
26
27 /**
28 * A transformer which transforms objects which are instances of a type into
29 * other defined objects based on this class' <code>mapping</code> property.
30 * The mapping property has types (instances of {@link java.lang.Class}) as keys and
31 * objects as values.
32 *
33 * @author Matthew Sgarlata
34 * @since June 15, 2005
35 */
36 public class ArbitraryTypeMappingConverter extends BaseTransformer implements DecoratedConverter {
37
38 private static final Class[] DESTINATION_CLASSES = new Class[] { Object.class };
39
40 private Map mapping;
41
42 /**
43 * {@inheritDoc}
44 */
45 protected Object convertImpl(Class destinationClass, Object source,
46 Locale locale) throws Exception {
47 Iterator iterator = getMapping().keySet().iterator();
48 while (iterator.hasNext()) {
49 Class type = (Class) iterator.next();
50 if (source == null) {
51 if (type == null) {
52 return getMapping().get(type);
53 }
54 }
55 else {
56 if (type != null && type.isAssignableFrom(source.getClass())) {
57 return getMapping().get(type);
58 }
59 }
60 }
61
62 throw new TransformationException(destinationClass, source);
63 }
64
65 /**
66 * {@inheritDoc}
67 */
68 protected Class[] getSourceClassesImpl() throws Exception {
69 if (ObjectUtils.isEmpty(mapping)) {
70 throw new IllegalStateException("The mapping property of this converter must be set");
71 }
72 return (Class[]) getMapping().keySet().toArray(new Class[getMapping().keySet().size()]);
73 }
74
75 /**
76 * {@inheritDoc}
77 */
78 protected Class[] getDestinationClassesImpl() throws Exception {
79 return DESTINATION_CLASSES;
80 }
81
82 /**
83 * {@inheritDoc}
84 */
85 protected boolean isWrappingRuntimeExceptions() {
86 return true;
87 }
88
89 /**
90 * Returns the mapping of types to objects
91 * @return Returns the mapping.
92 */
93 public Map getMapping() {
94 return mapping;
95 }
96
97 /**
98 * @param mapping The mapping to set.
99 */
100 public void setMapping(Map mapping) {
101 this.mapping = mapping;
102 }
103
104 }