1
2
3
4
5
6
7
8
9
10
11 package org.mule.expression;
12
13 import org.mule.api.MuleMessage;
14 import org.mule.api.expression.ExpressionEvaluator;
15 import org.mule.api.expression.RequiredValueException;
16 import org.mule.config.i18n.CoreMessages;
17 import org.mule.util.StringUtils;
18
19 import java.util.HashMap;
20 import java.util.Map;
21
22 import static org.mule.expression.ExpressionConstants.DELIM;
23 import static org.mule.expression.ExpressionConstants.OPTIONAL_ARGUMENT;
24
25
26
27
28
29 public class MapPayloadExpressionEvaluator implements ExpressionEvaluator
30 {
31 public static final String NAME = "map-payload";
32
33 public Object evaluate(String expression, MuleMessage message)
34 {
35 Object payload = message.getPayload();
36
37 if (!(payload instanceof Map))
38 {
39 return null;
40 }
41
42 if (expression.indexOf(DELIM) > -1)
43 {
44
45 String[] strings = StringUtils.splitAndTrim(expression, DELIM);
46 Map<String, Object> result = new HashMap<String, Object>(strings.length);
47
48 for (String s : strings)
49 {
50 Object val = getValue(s, (Map) payload);
51 if (val != null)
52 {
53 if (s.endsWith(OPTIONAL_ARGUMENT))
54 {
55 s = s.substring(0, s.length() - OPTIONAL_ARGUMENT.length());
56 }
57 result.put(s, val);
58 }
59 }
60 return result;
61 }
62 else
63 {
64 return getValue(expression, (Map)payload);
65 }
66 }
67
68 protected Object getValue(String key, Map map)
69 {
70 boolean required;
71 if (key.endsWith(OPTIONAL_ARGUMENT))
72 {
73 key = key.substring(0, key.length() - OPTIONAL_ARGUMENT.length());
74 required = false;
75 }
76 else
77 {
78 required = true;
79 }
80 Object val = map.get(key);
81 if (val != null)
82 {
83 return val;
84 }
85 else if (required)
86 {
87 throw new RequiredValueException(CoreMessages.expressionEvaluatorReturnedNull(NAME, key));
88 }
89 return null;
90 }
91
92
93
94
95 public String getName()
96 {
97 return NAME;
98 }
99
100
101
102
103 public void setName(String name)
104 {
105 throw new UnsupportedOperationException();
106 }
107
108 }