KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > bean > modifier > TrimStringsBeanModifier


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.bean.modifier;
4
5 import jodd.bean.BeanUtil;
6 import jodd.introspector.ClassDescriptor;
7 import jodd.introspector.DefaultIntrospector;
8
9 /**
10  * Simple bean modifier that trims all String parameters of given java bean object.
11  */

12 public class TrimStringsBeanModifier implements BeanModifier {
13
14     public void modify(Object JavaDoc bean) {
15         if (bean == null) {
16             return;
17         }
18         ClassDescriptor bcd = DefaultIntrospector.lookup(bean.getClass());
19         String JavaDoc[] getters = bcd.getAllBeanGetterNames();
20         for (int i = 0; i < getters.length; i++) {
21             if (bcd.getBeanSetter(getters[i]) == null) {
22                 continue;
23             }
24             onProperty(bean, getters[i]);
25         }
26     }
27
28     void onProperty(Object JavaDoc obj, String JavaDoc name) {
29         try {
30             Object JavaDoc value = BeanUtil.getProperty(obj, name);
31             if (value == null) {
32                 return;
33             }
34             if (value instanceof String JavaDoc) { // trim String parameter
35
value = ((String JavaDoc)value).trim();
36                 BeanUtil.setProperty(obj, name, value);
37             } else if (value.getClass().isArray() == true) {
38                 if (value instanceof String JavaDoc[]) { // trim String[] parameter
39
String JavaDoc[] valueArray = (String JavaDoc[]) value;
40                     for (int i = 0; i < valueArray.length; i++) {
41                         valueArray[i] = valueArray[i].trim();
42                     }
43                 } else {
44                     Object JavaDoc[] valueArray = (Object JavaDoc[]) value; // trim Strings in Object[] parameter
45
for (int i = 0; i < valueArray.length; i++) {
46                         if (valueArray[i] instanceof String JavaDoc) {
47                             valueArray[i] = ((String JavaDoc)valueArray[i]).trim();
48                         }
49                     }
50                 }
51             }
52         } catch (Exception JavaDoc ex) {
53             // cant trim property, just go out.
54
}
55     }
56 }
57
Popular Tags