1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.nuiton.decorator;
23
24 import org.apache.commons.jxpath.DynamicPropertyHandler;
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27
28 import java.util.Collection;
29 import java.util.Iterator;
30 import java.util.Map;
31 import java.util.Set;
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54 public class MapPropertyHandler implements DynamicPropertyHandler {
55
56
57 private static final Log log =
58 LogFactory.getLog(MapPropertyHandler.class);
59
60 @Override
61 public String[] getPropertyNames(Object object) {
62 Map<?, ?> map = (Map<?, ?>) object;
63 Set<?> set = map.keySet();
64 String[] names = new String[set.size()];
65 Iterator<?> it = set.iterator();
66 for (int i = 0; i < names.length; i++) {
67 Object o = it.next();
68 names[i] = getKey(o);
69 }
70 return names;
71 }
72
73 @Override
74 public Object getProperty(Object object, String propertyName) {
75 Map<?, ?> map = (Map<?, ?>) object;
76 boolean getKey = false;
77 Object property0;
78 if (propertyName.startsWith("value:")) {
79 propertyName = propertyName.substring(6);
80 if (log.isDebugEnabled()) {
81 log.debug("property value name " + propertyName);
82 }
83 property0 = getPropertyValue(map, propertyName);
84 if (log.isDebugEnabled()) {
85 log.debug("property value = " + property0);
86 }
87 return property0;
88 }
89 if (propertyName.startsWith("key:")) {
90 propertyName = propertyName.substring(4);
91 getKey = true;
92 }
93 property0 = getPropertyKey(map, propertyName);
94 Object result = null;
95 if (property0 != null) {
96 if (getKey) {
97 result = property0;
98 } else {
99 result = map.get(property0);
100 }
101 }
102 return result;
103 }
104
105 @Override
106 public void setProperty(Object object, String propertyName, Object value) {
107 Map map = (Map) object;
108 Object property0 = getPropertyKey(map, propertyName);
109 if (property0 != null) {
110 map.put(property0, value);
111 }
112 }
113
114
115
116
117
118
119
120
121
122
123
124 public Object getPropertyKey(Map<?, ?> map, String key) {
125 Set<?> set = map.keySet();
126 for (Object o : set) {
127 String k = getKey(o);
128 if (key.equals(k)) {
129 return o;
130 }
131 }
132 return null;
133 }
134
135
136
137
138
139
140
141
142
143
144
145
146 public Object getPropertyValue(Map<?, ?> map, String value) {
147 Collection<?> set = map.values();
148 for (Object o : set) {
149 if (o instanceof Iterable<?>) {
150 Iterable<?> c = (Iterable<?>) o;
151 for (Object oo : c) {
152 String k = getKey(oo);
153 if (value.equals(k)) {
154 return oo;
155 }
156 }
157 continue;
158 }
159 String k = getKey(o);
160 if (value.equals(k)) {
161 return o;
162 }
163 }
164 return null;
165 }
166
167
168
169
170
171
172
173 protected String getKey(Object o) {
174 String k = String.valueOf(o);
175 return k;
176 }
177 }