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