1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.commons.jelly.tags.core;
17
18 import java.lang.reflect.InvocationTargetException;
19 import java.util.Map;
20
21 import org.apache.commons.beanutils.BeanUtils;
22
23 import org.apache.commons.jelly.JellyException;
24 import org.apache.commons.jelly.JellyTagException;
25 import org.apache.commons.jelly.MissingAttributeException;
26 import org.apache.commons.jelly.MapTagSupport;
27 import org.apache.commons.jelly.XMLOutput;
28 import org.apache.commons.jelly.impl.BeanSource;
29
30 /***
31 * A tag which sets the bean properties on the given bean.
32 * So if you used it as follows, for example using the <j:new> tag.
33 * <pre>
34 * <j:new className="com.acme.Person" var="person"/>
35 * <j:setProperties object="${person}" name="James" location="${loc}"/>
36 * </pre>
37 * Then it would set the name and location properties on the bean denoted by
38 * the expression ${person}.
39 * <p>
40 * This tag can also be nested inside a bean tag such as the <useBean> tag
41 * or a JellySwing tag to set one or more properties, maybe inside some conditional
42 * logic.
43 *
44 * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
45 * @version $Revision: 155420 $
46 */
47 public class SetPropertiesTag extends MapTagSupport {
48
49 public SetPropertiesTag(){
50 }
51
52
53
54 public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException {
55 Map attributes = getAttributes();
56 Object bean = attributes.remove( "object" );
57 if ( bean == null ) {
58
59 BeanSource tag = (BeanSource) findAncestorWithClass(BeanSource.class);
60 if (tag != null) {
61 try {
62 bean = tag.getBean();
63 } catch (JellyException e) {
64 throw new JellyTagException(e);
65 }
66 }
67 if (bean == null) {
68 throw new MissingAttributeException("bean");
69 }
70 }
71 setBeanProperties(bean, attributes);
72 }
73
74
75
76
77 /***
78 * Sets the properties on the bean. Derived tags could implement some custom
79 * type conversion etc.
80 */
81 protected void setBeanProperties(Object bean, Map attributes) throws JellyTagException {
82 try {
83 BeanUtils.populate(bean, attributes);
84 } catch (IllegalAccessException e) {
85 throw new JellyTagException("could not set the properties on a bean",e);
86 } catch (InvocationTargetException e) {
87 throw new JellyTagException("could not set the properties on a bean",e);
88 }
89 }
90 }