1 16 17 package org.apache.commons.beanutils; 18 19 import org.apache.commons.collections.Transformer; 20 import org.apache.commons.logging.Log; 21 import org.apache.commons.logging.LogFactory; 22 23 import java.lang.reflect.InvocationTargetException ; 24 25 26 71 public class BeanToPropertyValueTransformer implements Transformer { 72 73 74 private final Log log = LogFactory.getLog(this.getClass()); 75 76 77 private String propertyName; 78 79 92 private boolean ignoreNull; 93 94 103 public BeanToPropertyValueTransformer(String propertyName) { 104 this(propertyName, false); 105 } 106 107 119 public BeanToPropertyValueTransformer(String propertyName, boolean ignoreNull) { 120 super(); 121 122 if ((propertyName != null) && (propertyName.length() > 0)) { 123 this.propertyName = propertyName; 124 this.ignoreNull = ignoreNull; 125 } else { 126 throw new IllegalArgumentException ( 127 "propertyName cannot be null or empty"); 128 } 129 } 130 131 147 public Object transform(Object object) { 148 149 Object propertyValue = null; 150 151 try { 152 propertyValue = PropertyUtils.getProperty(object, propertyName); 153 } catch (IllegalArgumentException e) { 154 final String errorMsg = "Problem during transformation. Null value encountered in property path..."; 155 156 if (ignoreNull) { 157 log.warn("WARNING: " + errorMsg, e); 158 } else { 159 log.error("ERROR: " + errorMsg, e); 160 throw e; 161 } 162 } catch (IllegalAccessException e) { 163 final String errorMsg = "Unable to access the property provided."; 164 log.error(errorMsg, e); 165 throw new IllegalArgumentException (errorMsg); 166 } catch (InvocationTargetException e) { 167 final String errorMsg = "Exception occurred in property's getter"; 168 log.error(errorMsg, e); 169 throw new IllegalArgumentException (errorMsg); 170 } catch (NoSuchMethodException e) { 171 final String errorMsg = "No property found for name [" + 172 propertyName + "]"; 173 log.error(errorMsg, e); 174 throw new IllegalArgumentException (errorMsg); 175 } 176 177 return propertyValue; 178 } 179 180 185 public String getPropertyName() { 186 return propertyName; 187 } 188 189 202 public boolean isIgnoreNull() { 203 return ignoreNull; 204 } 205 } 206 | Popular Tags |