1 /*
2 * #%L
3 * Nuiton Decorator
4 * %%
5 * Copyright (C) 2011 CodeLutin, Tony Chemit
6 * %%
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Lesser Public License for more details.
16 *
17 * You should have received a copy of the GNU General Lesser Public
18 * License along with this program. If not, see
19 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
20 * #L%
21 */
22 package org.nuiton.decorator;
23
24 import org.apache.commons.beanutils.PropertyUtils;
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27
28 import java.beans.PropertyDescriptor;
29 import java.lang.reflect.Method;
30
31 /**
32 * Simple property decorator based on {@link String#format(String, Object...)}
33 * method.
34 * <p/>
35 * To use it, give him a class and the property name to render.
36 * <p/>
37 * For example :
38 * <pre>
39 * Decorator<Object> d = DecoratorUtil.newPropertyDecorator(PropertyDecorator.class,"property");
40 * </pre>
41 *
42 * @param <O> type of data to decorate
43 * @author tchemit <chemit@codelutin.com>
44 * @see Decorator
45 * @since 2.3
46 */
47 public class PropertyDecorator<O> extends Decorator<O> {
48
49 private static final long serialVersionUID = 1L;
50
51 /** Logger */
52 static private final Log log = LogFactory.getLog(PropertyDecorator.class);
53
54 /** name of property */
55 protected String property;
56
57 protected transient Method m;
58
59 @Override
60 public String toString(Object bean) {
61 try {
62 return getM().invoke(bean) + "";
63 } catch (Exception e) {
64 log.error("could not convert for reason : " + e, e);
65 return "";
66 }
67 }
68
69 public String getProperty() {
70 return property;
71 }
72
73 protected PropertyDecorator(Class<O> internalClass,
74 String property) throws NullPointerException {
75 super(internalClass);
76 if (property == null) {
77 throw new NullPointerException("property can not be null.");
78 }
79 this.property = property;
80 // init method
81 getM();
82 }
83
84 protected Method getM() {
85 if (m == null) {
86 for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(getType())) {
87 if (propertyDescriptor.getName().equals(property)) {
88 m = propertyDescriptor.getReadMethod();
89 break;
90 }
91 }
92 if (m == null) {
93 throw new IllegalArgumentException("could not find the property " + property + " in " + getType());
94 }
95 }
96 return m;
97 }
98 }