KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > riotfamily > common > beans > PropertyUtils


1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1
3  * The contents of this file are subject to the Mozilla Public License Version
4  * 1.1 (the "License"); you may not use this file except in compliance with
5  * the License. You may obtain a copy of the License at
6  * http://www.mozilla.org/MPL/
7  *
8  * Software distributed under the License is distributed on an "AS IS" basis,
9  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10  * for the specific language governing rights and limitations under the
11  * License.
12  *
13  * The Original Code is Riot.
14  *
15  * The Initial Developer of the Original Code is
16  * Neteye GmbH.
17  * Portions created by the Initial Developer are Copyright (C) 2006
18  * the Initial Developer. All Rights Reserved.
19  *
20  * Contributor(s):
21  * Felix Gnass [fgnass at neteye dot de]
22  *
23  * ***** END LICENSE BLOCK ***** */

24 package org.riotfamily.common.beans;
25
26 import java.beans.PropertyDescriptor JavaDoc;
27 import java.beans.PropertyEditor JavaDoc;
28 import java.lang.reflect.Method JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.Map JavaDoc;
35 import java.util.regex.Matcher JavaDoc;
36 import java.util.regex.Pattern JavaDoc;
37
38 import org.springframework.beans.BeanUtils;
39 import org.springframework.beans.FatalBeanException;
40 import org.springframework.util.Assert;
41 import org.springframework.util.ClassUtils;
42 import org.springframework.util.ReflectionUtils;
43 import org.springframework.util.StringUtils;
44
45 /**
46  * Utility class to access bean properties via relection.
47  */

48 public final class PropertyUtils {
49
50     private static DefaultPropertyEditorRegistry registry =
51             new DefaultPropertyEditorRegistry();
52
53     private static Pattern JavaDoc expressionPattern = Pattern.compile(
54             "\\$\\{(.*?)\\}");
55
56     private PropertyUtils() {
57     }
58
59     public static Object JavaDoc getProperty(Object JavaDoc bean, String JavaDoc name) {
60         if (bean == null) {
61             return null;
62         }
63         ProtectedBeanWrapper wrapper = new ProtectedBeanWrapper(bean);
64         return wrapper.getPropertyValue(name);
65     }
66     
67     public static Object JavaDoc getProperty(Object JavaDoc bean, String JavaDoc name,
68             Class JavaDoc requiredType) {
69         
70         Object JavaDoc value = getProperty(bean, name);
71         if (value != null) {
72             Assert.isInstanceOf(requiredType, value);
73         }
74         return value;
75     }
76
77     public static String JavaDoc getPropertyAsString(Object JavaDoc bean, String JavaDoc name) {
78         return convertToString(getProperty(bean, name));
79     }
80
81     public static void setProperty(Object JavaDoc bean, String JavaDoc name, Object JavaDoc value) {
82         ProtectedBeanWrapper wrapper = new ProtectedBeanWrapper(bean);
83         wrapper.setPropertyValue(name, value);
84     }
85
86     public static void setPropertyAsString(Object JavaDoc bean, String JavaDoc name, String JavaDoc s) {
87         Class JavaDoc type = getPropertyType(bean.getClass(), name);
88         Object JavaDoc value = convert(s, type);
89         setProperty(bean, name, value);
90     }
91
92     /**
93      * Returns a Map containing the bean's properties.
94      * @since 6.4
95      */

96     public static Map JavaDoc getProperties(Object JavaDoc bean) {
97         PropertyDescriptor JavaDoc[] pd = BeanUtils.getPropertyDescriptors(bean.getClass());
98         HashMap JavaDoc properties = new HashMap JavaDoc();
99         for (int i = 0; i < pd.length; i++) {
100             Object JavaDoc value = ReflectionUtils.invokeMethod(pd[i].getReadMethod(), bean);
101             properties.put(pd[i].getName(), value);
102         }
103         return properties;
104     }
105
106     /**
107      * Returns a Map containing the bean's properties.
108      * @since 6.4
109      */

110     public static Map JavaDoc getProperties(Object JavaDoc bean, String JavaDoc[] propertyNames) {
111         HashMap JavaDoc properties = new HashMap JavaDoc();
112         for (int i = 0; i < propertyNames.length; i++) {
113             String JavaDoc name = propertyNames[i];
114             properties.put(name, getProperty(bean, name));
115         }
116         return properties;
117     }
118
119     /**
120      * @since 6.4
121      */

122     public static String JavaDoc evaluate(String JavaDoc expression, Object JavaDoc bean) {
123         Matcher JavaDoc matcher = expressionPattern.matcher(expression);
124         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
125         while (matcher.find()) {
126             String JavaDoc property = matcher.group(1);
127             Object JavaDoc value = getProperty(bean, property);
128             matcher.appendReplacement(sb, convertToString(value));
129         }
130         matcher.appendTail(sb);
131         return sb.toString();
132     }
133
134     public static Object JavaDoc convert(String JavaDoc s, Class JavaDoc targetClass) {
135         if (targetClass.equals(String JavaDoc.class)) {
136             return s;
137         }
138         PropertyEditor JavaDoc pe = registry.findEditor(targetClass);
139         Assert.notNull(pe, "No PropertyEditor found for class: " + targetClass);
140         synchronized (pe) {
141             pe.setAsText(s);
142             return pe.getValue();
143         }
144     }
145
146     /**
147      * @since 6.4
148      */

149     public static String JavaDoc convertToString(Object JavaDoc value) {
150         if (value != null) {
151             if (!(value instanceof String JavaDoc)) {
152                 PropertyEditor JavaDoc pe = registry.findEditor(value.getClass());
153                 if (pe != null) {
154                     synchronized (pe) {
155                         pe.setValue(value);
156                         return pe.getAsText();
157                     }
158                 }
159             }
160             return value.toString();
161         }
162         return null;
163     }
164
165     /**
166      * @deprecated as of Riot 6.4, in favor of Spring's <code>BeanUtils.getPropertyDescriptor</code>.
167      */

168     public static PropertyDescriptor JavaDoc getPropertyDescriptor(
169             Class JavaDoc clazz, String JavaDoc property) {
170
171         return BeanUtils.getPropertyDescriptor(clazz, property);
172     }
173
174     public static Class JavaDoc getPropertyType(Class JavaDoc clazz, String JavaDoc property) {
175         PropertyDescriptor JavaDoc pd = BeanUtils.getPropertyDescriptor(clazz, property);
176         Assert.notNull(pd, "Property '" + property + "' not found in class " + clazz);
177         return pd.getPropertyType();
178     }
179
180     /**
181      * @since 6.4
182      */

183     public static Method JavaDoc findReadMethod(Class JavaDoc clazz, String JavaDoc property) {
184         String JavaDoc methodName = "get" + StringUtils.capitalize(property);
185         Method JavaDoc readMethod = BeanUtils.findDeclaredMethod(clazz, methodName, null);
186         if (readMethod != null) {
187             readMethod.setAccessible(true);
188         }
189         return readMethod;
190     }
191
192     /**
193      * @since 6.4
194      */

195     public static Method JavaDoc findWriteMethod(Class JavaDoc clazz, String JavaDoc property) {
196         String JavaDoc methodName = "set" + StringUtils.capitalize(property);
197         Method JavaDoc writeMethod = BeanUtils.findDeclaredMethodWithMinimalParameters(
198                 clazz, methodName);
199
200         if (writeMethod != null) {
201             writeMethod.setAccessible(true);
202         }
203         return writeMethod;
204     }
205
206     /**
207      * Returns the (super-)class where the given property is declared.
208      */

209     public static Class JavaDoc getDeclaringClass(Class JavaDoc clazz,
210             String JavaDoc property) {
211
212         PropertyDescriptor JavaDoc[] descriptors =
213                 BeanUtils.getPropertyDescriptors(clazz);
214
215         for (int i = 0; i < descriptors.length; i++) {
216             if (descriptors[i].getName().equals(property)) {
217                 Method JavaDoc getter = descriptors[i].getReadMethod();
218                 if (getter == null) {
219                     return clazz;
220                 }
221                 return getter.getDeclaringClass();
222             }
223         }
224         return ClassUtils.getUserClass(clazz);
225     }
226
227     /**
228      * Creates a new instance of the class specified by the given name.
229      * The method uses {@link ClassUtils#forName(String)} and
230      * {@link BeanUtils#instantiateClass(Class)} internally.
231      * ClassNotFoundExceptions are caught and re-thrown as
232      * {@link FatalBeanException}.
233      */

234     public static Object JavaDoc newInstance(String JavaDoc className) {
235         try {
236             Class JavaDoc clazz = ClassUtils.forName(className);
237             return BeanUtils.instantiateClass(clazz);
238         }
239         catch (ClassNotFoundException JavaDoc e) {
240             throw new FatalBeanException(e.getMessage(), e);
241         }
242     }
243
244     /**
245      * Partitions the given collection by inspecting the specified property
246      * of the contained items.
247      *
248      * @param c The collection to partition
249      * @param titleProperty The property to use for grouping
250      * @return A list of {@link ObjectGroup ObjectGroups}
251      */

252     public static List JavaDoc partition(Collection JavaDoc c, String JavaDoc titleProperty) {
253         ArrayList JavaDoc groups = new ArrayList JavaDoc();
254         Iterator JavaDoc it = c.iterator();
255         ObjectGroup group = null;
256         while (it.hasNext()) {
257             Object JavaDoc item = it.next();
258             Object JavaDoc title = getProperty(item, titleProperty);
259             if (group == null || (title != null
260                     && !title.equals(group.getTitle()))) {
261
262                 group = new ObjectGroup(title, item);
263                 groups.add(group);
264             }
265             else {
266                 group.add(item);
267             }
268         }
269         return groups;
270     }
271
272 }
273
Popular Tags