1 17 18 19 package org.apache.commons.digester; 20 21 22 import java.beans.PropertyDescriptor ; 23 24 import org.apache.commons.beanutils.BeanUtils; 25 import org.apache.commons.beanutils.DynaBean; 26 import org.apache.commons.beanutils.DynaProperty; 27 import org.apache.commons.beanutils.PropertyUtils; 28 29 30 42 43 public class BeanPropertySetterRule extends Rule { 44 45 46 48 49 58 public BeanPropertySetterRule(Digester digester, String propertyName) { 59 60 this(propertyName); 61 62 } 63 64 75 public BeanPropertySetterRule(Digester digester) { 76 77 this(); 78 79 } 80 81 86 public BeanPropertySetterRule(String propertyName) { 87 88 this.propertyName = propertyName; 89 90 } 91 92 98 public BeanPropertySetterRule() { 99 100 this((String )null); 101 102 } 103 104 106 107 110 protected String propertyName = null; 111 112 113 116 protected String bodyText = null; 117 118 119 121 122 132 public void body(String namespace, String name, String text) 133 throws Exception { 134 135 if (digester.log.isDebugEnabled()) { 137 digester.log.debug("[BeanPropertySetterRule]{" + 138 digester.match + "} Called with text '" + text + "'"); 139 } 140 141 bodyText = text.trim(); 142 143 } 144 145 146 158 public void end(String namespace, String name) throws Exception { 159 160 String property = propertyName; 161 162 if (property == null) { 163 property = name; 166 } 167 168 Object top = digester.peek(); 170 171 if (digester.log.isDebugEnabled()) { 173 digester.log.debug("[BeanPropertySetterRule]{" + digester.match + 174 "} Set " + top.getClass().getName() + " property " + 175 property + " with text " + bodyText); 176 } 177 178 if (top instanceof DynaBean) { 181 DynaProperty desc = 182 ((DynaBean) top).getDynaClass().getDynaProperty(property); 183 if (desc == null) { 184 throw new NoSuchMethodException 185 ("Bean has no property named " + property); 186 } 187 } else { 188 PropertyDescriptor desc = 189 PropertyUtils.getPropertyDescriptor(top, property); 190 if (desc == null) { 191 throw new NoSuchMethodException 192 ("Bean has no property named " + property); 193 } 194 } 195 196 BeanUtils.setProperty(top, property, bodyText); 198 199 } 200 201 202 205 public void finish() throws Exception { 206 207 bodyText = null; 208 209 } 210 211 212 215 public String toString() { 216 217 StringBuffer sb = new StringBuffer ("BeanPropertySetterRule["); 218 sb.append("propertyName="); 219 sb.append(propertyName); 220 sb.append("]"); 221 return (sb.toString()); 222 223 } 224 225 } 226 | Popular Tags |