1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.common.util.nullify;
17
18 import java.lang.reflect.InvocationTargetException;
19 import java.util.Arrays;
20 import java.util.List;
21
22 import org.apache.commons.beanutils.PropertyUtils;
23 import org.kuali.common.util.Str;
24 import org.kuali.common.util.property.Constants;
25 import org.springframework.util.Assert;
26
27 public class DefaultBeanNullifier implements Nullify {
28
29 Object bean;
30 List<String> properties;
31 List<String> nullTokens = Arrays.asList(Constants.NULL);
32 boolean caseSensitive = false;
33
34 @Override
35 public void nullify() {
36 Assert.notNull(bean, "bean cannot be null");
37 Assert.notNull(properties, "properties cannot be null");
38 Assert.notNull(nullTokens, "nullTokens cannot be null");
39
40 for (String property : properties) {
41 Object value = getProperty(bean, property);
42 if (isNullify(value, nullTokens, caseSensitive)) {
43 setProperty(bean, property, null);
44 }
45 }
46 }
47
48 protected boolean isNullify(Object value, List<String> nullTokens, boolean caseSensitive) {
49 if (value == null) {
50 return false;
51 } else {
52 return Str.contains(nullTokens, value.toString(), caseSensitive);
53 }
54 }
55
56 protected void setProperty(Object bean, String property, Object value) {
57 try {
58 PropertyUtils.setProperty(bean, property, value);
59 } catch (NoSuchMethodException e) {
60 throw new IllegalArgumentException(e);
61 } catch (InvocationTargetException e) {
62 throw new IllegalArgumentException(e);
63 } catch (IllegalAccessException e) {
64 throw new IllegalArgumentException(e);
65 }
66 }
67
68 protected Object getProperty(Object bean, String property) {
69 try {
70 return PropertyUtils.getProperty(bean, property);
71 } catch (NoSuchMethodException e) {
72 throw new IllegalArgumentException(e);
73 } catch (InvocationTargetException e) {
74 throw new IllegalArgumentException(e);
75 } catch (IllegalAccessException e) {
76 throw new IllegalArgumentException(e);
77 }
78 }
79
80 public Object getBean() {
81 return bean;
82 }
83
84 public void setBean(Object bean) {
85 this.bean = bean;
86 }
87
88 public List<String> getProperties() {
89 return properties;
90 }
91
92 public void setProperties(List<String> properties) {
93 this.properties = properties;
94 }
95
96 public List<String> getNullTokens() {
97 return nullTokens;
98 }
99
100 public void setNullTokens(List<String> nullTokens) {
101 this.nullTokens = nullTokens;
102 }
103
104 public boolean isCaseSensitive() {
105 return caseSensitive;
106 }
107
108 public void setCaseSensitive(boolean caseSensitive) {
109 this.caseSensitive = caseSensitive;
110 }
111
112 }