1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.jcr.node2bean.impl;
35
36 import info.magnolia.cms.core.MgnlNodeType;
37 import info.magnolia.cms.util.ContentUtil;
38 import info.magnolia.cms.util.SystemContentWrapper;
39 import info.magnolia.jcr.iterator.FilteringNodeIterator;
40 import info.magnolia.jcr.node2bean.Node2BeanException;
41 import info.magnolia.jcr.node2bean.Node2BeanTransformer;
42 import info.magnolia.jcr.node2bean.PropertyTypeDescriptor;
43 import info.magnolia.jcr.node2bean.TransformationState;
44 import info.magnolia.jcr.node2bean.TypeDescriptor;
45 import info.magnolia.jcr.node2bean.TypeMapping;
46 import info.magnolia.jcr.predicate.AbstractPredicate;
47 import info.magnolia.objectfactory.Classes;
48 import info.magnolia.objectfactory.ComponentProvider;
49
50 import java.lang.reflect.Array;
51 import java.lang.reflect.Constructor;
52 import java.lang.reflect.InvocationTargetException;
53 import java.lang.reflect.Method;
54 import java.text.MessageFormat;
55 import java.util.Collection;
56 import java.util.HashSet;
57 import java.util.Iterator;
58 import java.util.LinkedHashMap;
59 import java.util.LinkedList;
60 import java.util.List;
61 import java.util.Locale;
62 import java.util.Map;
63 import java.util.Queue;
64 import java.util.Set;
65 import java.util.regex.Pattern;
66
67 import javax.inject.Inject;
68 import javax.jcr.Node;
69 import javax.jcr.NodeIterator;
70 import javax.jcr.RepositoryException;
71
72 import org.apache.commons.beanutils.BeanUtilsBean;
73 import org.apache.commons.beanutils.Converter;
74 import org.apache.commons.beanutils.MethodUtils;
75 import org.apache.commons.beanutils.PropertyUtils;
76 import org.apache.commons.beanutils.PropertyUtilsBean;
77 import org.apache.commons.lang.LocaleUtils;
78 import org.apache.commons.lang.StringUtils;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81
82 import com.google.common.collect.Iterables;
83
84
85
86
87 public class Node2BeanTransformerImpl implements Node2BeanTransformer {
88
89 private static final Logger log = LoggerFactory.getLogger(Node2BeanTransformerImpl.class);
90
91 private final BeanUtilsBean beanUtilsBean;
92
93 private final Class<?> defaultListImpl;
94
95 private final Class<?> defaultSetImpl;
96
97 private final Class<?> defaultQueueImpl;
98
99 @Inject
100 public Node2BeanTransformerImpl() {
101 this(LinkedList.class, HashSet.class, LinkedList.class);
102 }
103
104 public Node2BeanTransformerImpl(Class<?> defaultListImpl, Class<?> defaultSetImpl, Class<?> defaultQueueImpl) {
105 this.defaultListImpl = defaultListImpl;
106 this.defaultSetImpl = defaultSetImpl;
107 this.defaultQueueImpl = defaultQueueImpl;
108
109
110
111
112
113 final EnumAwareConvertUtilsBean convertUtilsBean = new EnumAwareConvertUtilsBean();
114
115
116 convertUtilsBean.deregister(Class.class);
117
118 convertUtilsBean.register(new Converter() {
119 @Override
120 public Object convert(Class type, Object value) {
121 return new MessageFormat((String) value);
122 }
123 }, MessageFormat.class);
124
125 convertUtilsBean.register(new Converter() {
126 @Override
127 public Object convert(Class type, Object value) {
128 return Pattern.compile((String) value);
129 }
130 }, Pattern.class);
131
132 this.beanUtilsBean = new BeanUtilsBean(convertUtilsBean, new PropertyUtilsBean());
133 }
134
135 @Override
136 public TransformationState newState() {
137 return new TransformationStateImpl();
138 }
139
140 @Override
141 public TypeDescriptor resolveType(TypeMapping typeMapping, TransformationState state, ComponentProvider componentProvider) throws ClassNotFoundException, RepositoryException {
142 TypeDescriptor typeDscr = null;
143 Node node = state.getCurrentNode();
144
145 try {
146 if (node.hasProperty("class")) {
147 String className = node.getProperty("class").getString();
148 if (StringUtils.isBlank(className)) {
149 log.warn("Cannot resolve type for node [" + node + "] because class property has empty value.");
150 } else {
151 Class<?> clazz = Classes.getClassFactory().forName(className);
152 typeDscr = typeMapping.getTypeDescriptor(clazz);
153 }
154 }
155 } catch (RepositoryException e) {
156 log.warn("Can't read class property from node [{}]", node.getPath(), e);
157 }
158
159 if (typeDscr == null && state.getLevel() > 1) {
160 TypeDescriptor parentTypeDscr = state.getCurrentType();
161 PropertyTypeDescriptor propDscr;
162
163 if (parentTypeDscr.isMap() || parentTypeDscr.isCollection()) {
164 if (state.getLevel() > 2) {
165
166 String mapProperyName = state.peekNode(1).getName();
167 propDscr = state.peekType(1).getPropertyTypeDescriptor(mapProperyName, typeMapping);
168 if (propDscr != null) {
169 typeDscr = propDscr.getCollectionEntryType();
170 }
171 }
172 } else {
173 propDscr = state.getCurrentType().getPropertyTypeDescriptor(node.getName(), typeMapping);
174 if (propDscr != null) {
175 typeDscr = propDscr.getType();
176 }
177 }
178 }
179
180 typeDscr = onResolveType(typeMapping, state, typeDscr, componentProvider);
181
182 if (typeDscr != null) {
183
184 final Class<?> type = typeDscr.getType();
185 typeDscr = typeMapping.getTypeDescriptor(componentProvider.getImplementation(type));
186
187
188 Node2BeanTransformer customTransformer = typeDscr.getTransformer();
189 if (customTransformer != null && customTransformer != this) {
190 TypeDescriptor typeFoundByCustomTransformer = customTransformer.resolveType(typeMapping, state, componentProvider);
191
192
193
194 if (typeFoundByCustomTransformer != TypeMapping.MAP_TYPE) {
195
196 Class<?> implementation = componentProvider.getImplementation(typeFoundByCustomTransformer.getType());
197 typeDscr = typeMapping.getTypeDescriptor(implementation);
198 }
199 }
200 }
201
202 if (typeDscr == null || typeDscr.needsDefaultMapping()) {
203 if (typeDscr == null) {
204 log.debug("Was not able to resolve type for node [{}] will use a map", node);
205 }
206 typeDscr = TypeMapping.MAP_TYPE;
207 }
208 log.debug("Resolved type [{}] for node [{}]", typeDscr.getType(), node.getPath());
209
210 return typeDscr;
211 }
212
213 @Override
214 public NodeIterator getChildren(Node node) throws RepositoryException {
215
216 return new FilteringNodeIterator(node.getNodes(), new AbstractPredicate<Node>() {
217 @Override
218 public boolean evaluateTyped(Node t) {
219 try {
220 return !(t.getName().startsWith(MgnlNodeType.JCR_PREFIX) ||
221 t.getName().startsWith(MgnlNodeType.MGNL_PREFIX) ||
222 t.isNodeType(MgnlNodeType.NT_METADATA));
223 } catch (RepositoryException e) {
224 return false;
225 }
226 }
227 });
228 }
229
230 @Override
231 public Object newBeanInstance(TransformationState state, Map<String, Object> values, ComponentProvider componentProvider) throws Node2BeanException {
232
233
234 final Object bean = convertPropertyValue(state.getCurrentType().getType(), values);
235
236 if (bean == values) {
237 try {
238
239 values.remove("class");
240 final Class<?> type = state.getCurrentType().getType();
241 if (LinkedHashMap.class.equals(type)) {
242
243
244 return new LinkedHashMap();
245 } else if (Map.class.isAssignableFrom(type)) {
246
247 log.warn("someone wants another type of map ? " + type);
248 } else if (Collection.class.isAssignableFrom(type)) {
249
250 return type.newInstance();
251 }
252 return componentProvider.newInstance(type);
253 } catch (Throwable e) {
254 throw new Node2BeanException(e);
255 }
256 }
257 return bean;
258 }
259
260 @Override
261 public void initBean(TransformationState state, Map values) throws Node2BeanException {
262 Object bean = state.getCurrentBean();
263
264 Method init;
265 try {
266 init = bean.getClass().getMethod("init", new Class[] {});
267 try {
268 init.invoke(bean);
269 } catch (Exception e) {
270 throw new Node2BeanException("can't call init method", e);
271 }
272 } catch (SecurityException e) {
273 return;
274 } catch (NoSuchMethodException e) {
275 return;
276 }
277 log.debug("{} is initialized", bean);
278
279 }
280
281 @Override
282 public Object convertPropertyValue(Class<?> propertyType, Object value) throws Node2BeanException {
283 if (Class.class.equals(propertyType)) {
284 try {
285 return Classes.getClassFactory().forName(value.toString());
286 } catch (ClassNotFoundException e) {
287 log.error("Can't convert property. Class for type [{}] not found.", propertyType);
288 throw new Node2BeanException(e);
289 }
290 }
291
292 if (Locale.class.equals(propertyType)) {
293 if (value instanceof String) {
294 String localeStr = (String) value;
295 if (StringUtils.isNotEmpty(localeStr)) {
296 return LocaleUtils.toLocale(localeStr);
297 }
298 }
299 }
300
301 if ((Collection.class.equals(propertyType)) && (value instanceof Map)) {
302
303 return ((Map) value).values();
304 }
305
306
307 if ((String.class.equals(propertyType)) && (value instanceof Map) && (((Map) value).size() == 1)) {
308 return ((Map) value).values().iterator().next();
309 }
310
311 return value;
312 }
313
314
315
316
317
318 protected TypeDescriptor onResolveType(TypeMapping typeMapping, TransformationState state, TypeDescriptor resolvedType, ComponentProvider componentProvider) {
319 return resolvedType;
320 }
321
322 @Override
323 public void setProperty(TypeMapping mapping, TransformationState state, PropertyTypeDescriptor descriptor, Map<String, Object> values) throws RepositoryException {
324 String propertyName = descriptor.getName();
325 if (propertyName.equals("class")) {
326 return;
327 }
328 Object value = values.get(propertyName);
329 Object bean = state.getCurrentBean();
330
331 if (propertyName.equals("content") && value == null) {
332
333
334 value = new SystemContentWrapper(ContentUtil.asContent((state.getCurrentNode())));
335 } else if (propertyName.equals("name") && value == null) {
336 value = state.getCurrentNode().getName();
337 } else if (propertyName.equals("className") && value == null) {
338 value = values.get("class");
339 }
340
341
342 if (value == null) {
343 return;
344 }
345
346 log.debug("try to set {}.{} with value {}", new Object[] {bean, propertyName, value});
347
348 if (!(bean instanceof Map)) {
349 try {
350 PropertyTypeDescriptor dscr = mapping.getPropertyTypeDescriptor(bean.getClass(), propertyName);
351 if (dscr.getType() != null) {
352
353
354 if (dscr.isCollection() || dscr.isMap() || dscr.isArray()) {
355 log.debug("{} is of type collection, map or array", propertyName);
356 if (dscr.getWriteMethod() != null) {
357 Method method = dscr.getWriteMethod();
358 clearCollection(bean, propertyName);
359 if (dscr.isMap()) {
360 method.invoke(bean, value);
361 } else if (dscr.isArray()){
362 Class<?> entryClass = dscr.getCollectionEntryType().getType();
363 Collection<Object> list = new LinkedList<Object>(((Map<Object, Object>) value).values());
364
365 Object[] arr = (Object[]) Array.newInstance(entryClass, list.size());
366 for (int i = 0; i < arr.length; i++) {
367 arr[i] = Iterables.get(list, i);
368 }
369 method.invoke(bean, new Object[] {arr});
370 } else if (dscr.isCollection()) {
371 if (value instanceof Map) {
372 value = createCollectionFromMap((Map<Object, Object>) value, dscr.getType().getType());
373 }
374 method.invoke(bean, value);
375 }
376 return;
377 } else if (dscr.getAddMethod() != null) {
378 Method method = dscr.getAddMethod();
379 clearCollection(bean, propertyName);
380 Class<?> entryClass = dscr.getCollectionEntryType().getType();
381
382 log.warn("Will use deprecated add method [" + method.getName() + "] to populate [" + propertyName + "] in bean class [" + bean.getClass().getName() + "].");
383 for (Iterator<Object> iter = ((Map<Object, Object>) value).keySet().iterator(); iter.hasNext();) {
384 Object key = iter.next();
385 Object entryValue = ((Map<Object, Object>) value).get(key);
386 entryValue = convertPropertyValue(entryClass, entryValue);
387 if (dscr.isCollection() || dscr.isArray()) {
388 log.debug("will add value {}", entryValue);
389 method.invoke(bean, new Object[] { entryValue });
390 }
391
392 else {
393 log.debug("will add key {} with value {}", key, entryValue);
394 method.invoke(bean, new Object[] { key, entryValue });
395 }
396 }
397 return;
398 }
399 if (dscr.isCollection()) {
400 log.debug("transform the values to a collection", propertyName);
401 value = ((Map<Object, Object>) value).values();
402 }
403 } else {
404 value = convertPropertyValue(dscr.getType().getType(), value);
405 }
406 }
407 } catch (Exception e) {
408 if (log.isDebugEnabled()) {
409 log.debug("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
410 new Object[] { propertyName, value, bean.getClass().getName(),
411 state.getCurrentNode().getPath(), e.toString() });
412 } else {
413 log.error("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
414 new Object[] {propertyName, value, bean.getClass().getName(),
415 state.getCurrentNode().getPath(), e.toString()});
416 }
417 }
418 }
419
420 try {
421
422
423
424
425
426
427 beanUtilsBean.setProperty(bean, propertyName, value);
428 } catch (Exception e) {
429 if (log.isDebugEnabled()) {
430 log.debug("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
431 new Object[] { propertyName, value, bean.getClass().getName(),
432 state.getCurrentNode().getPath(), e.toString() });
433 } else {
434 log.error("Can't set property [{}] to value [{}] in bean [{}] for node {} due to {}",
435 new Object[] {propertyName, value, bean.getClass().getName(),
436 state.getCurrentNode().getPath(), e.toString()});
437 }
438 }
439 }
440
441
442
443
444
445 private void clearCollection(Object bean, String propertyName) {
446 log.debug("clearing the current content of the collection/map");
447 try {
448 Object col = PropertyUtils.getProperty(bean, propertyName);
449 if (col != null) {
450 MethodUtils.invokeExactMethod(col, "clear", new Object[] {});
451 }
452 } catch (Exception e) {
453 log.debug("no clear method found on collection {}", propertyName);
454 }
455 }
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471 protected Collection<?> createCollectionFromMap(Map<?, ?> map, Class<?> clazz) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
472 Collection<?> collection = null;
473 Constructor<?> constructor = null;
474 if (clazz.isInterface()) {
475
476 if (List.class.isAssignableFrom(clazz)) {
477 constructor = defaultListImpl.getConstructor(Collection.class);
478 } else if (clazz.isAssignableFrom(Queue.class)) {
479 constructor = defaultQueueImpl.getConstructor(Collection.class);
480 } else if (Set.class.isAssignableFrom(clazz)) {
481 constructor = defaultSetImpl.getConstructor(Collection.class);
482 }
483 } else {
484 if (Collection.class.isAssignableFrom(clazz)) {
485 constructor = clazz.getConstructor(Collection.class);
486 }
487 }
488 if (constructor != null) {
489 collection = (Collection<?>) constructor.newInstance(map.values());
490 }
491 return collection;
492 }
493
494 }