1
2
3
4
5
6
7
8
9
10 package org.mule.transformer.simple;
11
12 import org.mule.api.lifecycle.InitialisationException;
13 import org.mule.api.transformer.DiscoverableTransformer;
14 import org.mule.api.transformer.TransformerException;
15 import org.mule.config.i18n.CoreMessages;
16 import org.mule.transformer.AbstractTransformer;
17 import org.mule.transformer.types.DataTypeFactory;
18 import org.mule.util.BeanUtils;
19 import org.mule.util.ClassUtils;
20
21 import java.util.Map;
22
23
24
25
26
27
28
29 public class MapToBean extends AbstractTransformer implements DiscoverableTransformer
30 {
31
32
33
34 public static final String CLASS_PROPERTY = "className";
35
36 private int priorityWeighting = DiscoverableTransformer.DEFAULT_PRIORITY_WEIGHTING;
37
38 public MapToBean()
39 {
40 registerSourceType(DataTypeFactory.create(Map.class));
41 setReturnDataType(DataTypeFactory.OBJECT);
42 }
43
44 @Override
45 public void initialise() throws InitialisationException
46 {
47 super.initialise();
48 if(getReturnClass().equals(Object.class))
49 {
50 throw new InitialisationException(CoreMessages.propertiesNotSet("returnClass"), this);
51 }
52 }
53
54 @Override
55 protected Object doTransform(Object src, String encoding) throws TransformerException
56 {
57 try
58 {
59 Map props = (Map)src;
60 String c = (String)props.remove(CLASS_PROPERTY);
61 Class clazz = getReturnClass();
62 if(c==null && clazz.equals(Object.class))
63 {
64 throw new TransformerException(CoreMessages.transforemrMapBeanClassNotSet());
65 }
66 else if (c!=null)
67 {
68 clazz = ClassUtils.loadClass(c, getClass());
69 }
70
71 Object result = ClassUtils.instanciateClass(clazz, ClassUtils.NO_ARGS);
72 BeanUtils.populate(result, props);
73
74 return result;
75 }
76 catch (Exception e)
77 {
78 throw new TransformerException(this, e);
79 }
80 }
81
82 public int getPriorityWeighting()
83 {
84 return priorityWeighting;
85 }
86
87 public void setPriorityWeighting(int weighting)
88 {
89 priorityWeighting = weighting;
90 }
91 }