1 package org.apache.commons.digester3;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import static java.lang.String.format;
23 import static org.apache.commons.beanutils.BeanUtils.setProperty;
24 import static org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptor;
25
26 import java.beans.PropertyDescriptor;
27
28 import org.apache.commons.beanutils.DynaBean;
29 import org.apache.commons.beanutils.DynaProperty;
30 import org.xml.sax.Attributes;
31
32
33
34
35
36 public class SetPropertyRule
37 extends Rule
38 {
39
40
41
42
43
44
45
46
47
48 public SetPropertyRule( String name, String value )
49 {
50 this.name = name;
51 this.value = value;
52 }
53
54
55
56
57
58
59 protected String name = null;
60
61
62
63
64 protected String value = null;
65
66
67
68
69
70
71 @Override
72 public void begin( String namespace, String name, Attributes attributes )
73 throws Exception
74 {
75 if ( attributes.getLength() == 0 )
76 {
77 return;
78 }
79
80
81 String actualName = null;
82 String actualValue = null;
83 for ( int i = 0; i < attributes.getLength(); i++ )
84 {
85 String attributeName = attributes.getLocalName( i );
86 if ( "".equals( attributeName ) )
87 {
88 attributeName = attributes.getQName( i );
89 }
90 String value = attributes.getValue( i );
91 if ( attributeName.equals( this.name ) )
92 {
93 actualName = value;
94 }
95 else if ( attributeName.equals( this.value ) )
96 {
97 actualValue = value;
98 }
99 }
100
101
102 Object top = getDigester().peek();
103
104
105 if ( getDigester().getLogger().isDebugEnabled() )
106 {
107 getDigester().getLogger().debug( format( "[SetPropertiesRule]{%s} Set %s property %s to %s",
108 getDigester().getMatch(),
109 top.getClass().getName(),
110 actualName,
111 actualValue ) );
112 }
113
114
115
116
117
118
119 if ( top instanceof DynaBean )
120 {
121 DynaProperty desc = ( (DynaBean) top ).getDynaClass().getDynaProperty( actualName );
122 if ( desc == null )
123 {
124 throw new NoSuchMethodException( "Bean has no property named " + actualName );
125 }
126 }
127 else
128
129 {
130 PropertyDescriptor desc = getPropertyDescriptor( top, actualName );
131 if ( desc == null )
132 {
133 throw new NoSuchMethodException( "Bean has no property named " + actualName );
134 }
135 }
136
137
138 setProperty( top, actualName, actualValue );
139 }
140
141
142
143
144 @Override
145 public String toString()
146 {
147 return format( "SetPropertyRule[name=%s, value=%s]", name, value );
148 }
149
150 }