1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.tomcat.util.digester;
18
19 import org.apache.tomcat.util.IntrospectionUtils;
20 import org.xml.sax.Attributes;
21
22 /**
23  * <p>Rule implementation that calls a method on an object on the stack
24  * (normally the top/parent object), passing arguments collected from
25  * subsequent <code>CallParamRule</code> rules or from the body of this
26  * element. </p>
27  *
28  * <p>By using {@link #CallMethodRule(String methodName)}
29  * a method call can be made to a method which accepts no
30  * arguments.</p>
31  *
32  * <p>Incompatible method parameter types are converted
33  * using <code>org.apache.commons.beanutils.ConvertUtils</code>.
34  * </p>
35  *
36  * <p>This rule now uses
37  * <a href="https://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/MethodUtils.html">
38  * org.apache.commons.beanutils.MethodUtils#invokeMethod
39  * </a> by default.
40  * This increases the kinds of methods successfully and allows primitives
41  * to be matched by passing in wrapper classes.
42  * There are rare cases when org.apache.commons.beanutils.MethodUtils#invokeExactMethod
43  * (the old default) is required.
44  * This method is much stricter in its reflection.
45  * Setting the <code>UseExactMatch</code> to true reverts to the use of this
46  * method.</p>
47  *
48  * <p>Note that the target method is invoked when the  <i>end</i> of
49  * the tag the CallMethodRule fired on is encountered, <i>not</i> when the
50  * last parameter becomes available. This implies that rules which fire on
51  * tags nested within the one associated with the CallMethodRule will
52  * fire before the CallMethodRule invokes the target method. This behaviour is
53  * not configurable. </p>
54  *
55  * <p>Note also that if a CallMethodRule is expecting exactly one parameter
56  * and that parameter is not available (eg CallParamRule is used with an
57  * attribute name but the attribute does not exist) then the method will
58  * not be invoked. If a CallMethodRule is expecting more than one parameter,
59  * then it is always invoked, regardless of whether the parameters were
60  * available or not (missing parameters are passed as null values).</p>
61  */

62 public class CallMethodRule extends Rule {
63
64     // ----------------------------------------------------------- Constructors
65
66     /**
67      * Construct a "call method" rule with the specified method name.  The
68      * parameter types (if any) default to java.lang.String.
69      *
70      * @param methodName Method name of the parent method to call
71      * @param paramCount The number of parameters to collect, or
72      *  zero for a single argument from the body of this element.
73      */

74     public CallMethodRule(String methodName, int paramCount) {
75         this(0, methodName, paramCount);
76     }
77
78
79     /**
80      * Construct a "call method" rule with the specified method name.  The
81      * parameter types (if any) default to java.lang.String.
82      *
83      * @param targetOffset location of the target object. Positive numbers are
84      * relative to the top of the digester object stack. Negative numbers
85      * are relative to the bottom of the stack. Zero implies the top
86      * object on the stack.
87      * @param methodName Method name of the parent method to call
88      * @param paramCount The number of parameters to collect, or
89      *  zero for a single argument from the body of this element.
90      */

91     public CallMethodRule(int targetOffset, String methodName, int paramCount) {
92         this.targetOffset = targetOffset;
93         this.methodName = methodName;
94         this.paramCount = paramCount;
95         if (paramCount == 0) {
96             this.paramTypes = new Class[] { String.class };
97         } else {
98             this.paramTypes = new Class[paramCount];
99             for (int i = 0; i < this.paramTypes.length; i++) {
100                 this.paramTypes[i] = String.class;
101             }
102         }
103     }
104
105
106     /**
107      * Construct a "call method" rule with the specified method name.
108      * The method should accept no parameters.
109      *
110      * @param methodName Method name of the parent method to call
111      */

112     public CallMethodRule(String methodName) {
113         this(0, methodName, 0, null);
114     }
115
116
117     /**
118      * Construct a "call method" rule with the specified method name and
119      * parameter types. If <code>paramCount</code> is set to zero the rule
120      * will use the body of this element as the single argument of the
121      * method, unless <code>paramTypes</code> is null or empty, in this
122      * case the rule will call the specified method with no arguments.
123      *
124      * @param targetOffset location of the target object. Positive numbers are
125      * relative to the top of the digester object stack. Negative numbers
126      * are relative to the bottom of the stack. Zero implies the top
127      * object on the stack.
128      * @param methodName Method name of the parent method to call
129      * @param paramCount The number of parameters to collect, or
130      *  zero for a single argument from the body of this element
131      * @param paramTypes The Java classes that represent the
132      *  parameter types of the method arguments
133      *  (if you wish to use a primitive type, specify the corresponding
134      *  Java wrapper class instead, such as <code>java.lang.Boolean.TYPE</code>
135      *  for a <code>boolean</code> parameter)
136      */

137     public CallMethodRule(int targetOffset, String methodName, int paramCount,
138             Class<?> paramTypes[]) {
139
140         this.targetOffset = targetOffset;
141         this.methodName = methodName;
142         this.paramCount = paramCount;
143         if (paramTypes == null) {
144             this.paramTypes = new Class[paramCount];
145             for (int i = 0; i < this.paramTypes.length; i++) {
146                 this.paramTypes[i] = String.class;
147             }
148         } else {
149             this.paramTypes = new Class[paramTypes.length];
150             System.arraycopy(paramTypes, 0, this.paramTypes, 0, this.paramTypes.length);
151         }
152     }
153
154
155     // ----------------------------------------------------- Instance Variables
156
157     /**
158      * The body text collected from this element.
159      */

160     protected String bodyText = null;
161
162
163     /**
164      * location of the target object for the call, relative to the
165      * top of the digester object stack. The default value of zero
166      * means the target object is the one on top of the stack.
167      */

168     protected final int targetOffset;
169
170
171     /**
172      * The method name to call on the parent object.
173      */

174     protected final String methodName;
175
176
177     /**
178      * The number of parameters to collect from <code>MethodParam</code> rules.
179      * If this value is zero, a single parameter will be collected from the
180      * body of this element.
181      */

182     protected final int paramCount;
183
184
185     /**
186      * The parameter types of the parameters to be collected.
187      */

188     protected Class<?> paramTypes[] = null;
189
190
191     /**
192      * Should <code>MethodUtils.invokeExactMethod</code> be used for reflection.
193      */

194     protected boolean useExactMatch = false;
195
196
197     // --------------------------------------------------------- Public Methods
198
199     /**
200      * Should <code>MethodUtils.invokeExactMethod</code>
201      * be used for the reflection.
202      * @return <code>true</code> if invokeExactMethod is used
203      */

204     public boolean getUseExactMatch() {
205         return useExactMatch;
206     }
207
208
209     /**
210      * Set whether <code>MethodUtils.invokeExactMethod</code>
211      * should be used for the reflection.
212      * @param useExactMatch The flag value
213      */

214     public void setUseExactMatch(boolean useExactMatch) {
215         this.useExactMatch = useExactMatch;
216     }
217
218
219     /**
220      * Process the start of this element.
221      *
222      * @param namespace the namespace URI of the matching element, or an
223      *   empty string if the parser is not namespace aware or the element has
224      *   no namespace
225      * @param name the local name if the parser is namespace aware, or just
226      *   the element name otherwise
227      * @param attributes The attribute list for this element
228      */

229     @Override
230     public void begin(String namespace, String name, Attributes attributes)
231             throws Exception {
232
233         // Push an array to capture the parameter values if necessary
234         if (paramCount > 0) {
235             Object parameters[] = new Object[paramCount];
236             for (int i = 0; i < parameters.length; i++) {
237                 parameters[i] = null;
238             }
239             digester.pushParams(parameters);
240         }
241
242     }
243
244
245     /**
246      * Process the body text of this element.
247      *
248      * @param namespace the namespace URI of the matching element, or an
249      *   empty string if the parser is not namespace aware or the element has
250      *   no namespace
251      * @param name the local name if the parser is namespace aware, or just
252      *   the element name otherwise
253      * @param bodyText The body text of this element
254      */

255     @Override
256     public void body(String namespace, String name, String bodyText)
257             throws Exception {
258
259         if (paramCount == 0) {
260             this.bodyText = bodyText.trim().intern();
261         }
262
263     }
264
265
266     /**
267      * Process the end of this element.
268      *
269      * @param namespace the namespace URI of the matching element, or an
270      *   empty string if the parser is not namespace aware or the element has
271      *   no namespace
272      * @param name the local name if the parser is namespace aware, or just
273      *   the element name otherwise
274      */

275     @SuppressWarnings("null"// parameters can't trigger NPE
276     @Override
277     public void end(String namespace, String name) throws Exception {
278
279         // Retrieve or construct the parameter values array
280         Object parameters[] = null;
281         if (paramCount > 0) {
282
283             parameters = (Object[]) digester.popParams();
284
285             if (digester.log.isTraceEnabled()) {
286                 for (int i=0,size=parameters.length;i<size;i++) {
287                     digester.log.trace("[CallMethodRule](" + i + ")" + parameters[i]) ;
288                 }
289             }
290
291             // In the case where the parameter for the method
292             // is taken from an attribute, and that attribute
293             // isn't actually defined in the source XML file,
294             // skip the method call
295             if (paramCount == 1 && parameters[0] == null) {
296                 return;
297             }
298
299         } else if (paramTypes != null && paramTypes.length != 0) {
300
301             // In the case where the parameter for the method
302             // is taken from the body text, but there is no
303             // body text included in the source XML file,
304             // skip the method call
305             if (bodyText == null) {
306                 return;
307             }
308
309             parameters = new Object[1];
310             parameters[0] = bodyText;
311         }
312
313         // Construct the parameter values array we will need
314         // We only do the conversion if the param value is a String and
315         // the specified paramType is not String.
316         Object paramValues[] = new Object[paramTypes.length];
317         for (int i = 0; i < paramTypes.length; i++) {
318             // convert nulls and convert stringy parameters
319             // for non-stringy param types
320             Object param = parameters[i];
321             // Tolerate null non-primitive values
322             if(null == param && !paramTypes[i].isPrimitive())
323                 paramValues[i] = null;
324             else if(param instanceof String &&
325                     !String.class.isAssignableFrom(paramTypes[i])) {
326
327                 paramValues[i] =
328                         IntrospectionUtils.convert((String) parameters[i], paramTypes[i]);
329             } else {
330                 paramValues[i] = parameters[i];
331             }
332         }
333
334         // Determine the target object for the method call
335         Object target;
336         if (targetOffset >= 0) {
337             target = digester.peek(targetOffset);
338         } else {
339             target = digester.peek( digester.getCount() + targetOffset );
340         }
341
342         if (target == null) {
343             StringBuilder sb = new StringBuilder();
344             sb.append("[CallMethodRule]{");
345             sb.append(digester.match);
346             sb.append("} Call target is null (");
347             sb.append("targetOffset=");
348             sb.append(targetOffset);
349             sb.append(",stackdepth=");
350             sb.append(digester.getCount());
351             sb.append(")");
352             throw new org.xml.sax.SAXException(sb.toString());
353         }
354
355         // Invoke the required method on the top object
356         if (digester.log.isDebugEnabled()) {
357             StringBuilder sb = new StringBuilder("[CallMethodRule]{");
358             sb.append(digester.match);
359             sb.append("} Call ");
360             sb.append(target.getClass().getName());
361             sb.append(".");
362             sb.append(methodName);
363             sb.append("(");
364             for (int i = 0; i < paramValues.length; i++) {
365                 if (i > 0) {
366                     sb.append(",");
367                 }
368                 if (paramValues[i] == null) {
369                     sb.append("null");
370                 } else {
371                     sb.append(paramValues[i].toString());
372                 }
373                 sb.append("/");
374                 if (paramTypes[i] == null) {
375                     sb.append("null");
376                 } else {
377                     sb.append(paramTypes[i].getName());
378                 }
379             }
380             sb.append(")");
381             digester.log.debug(sb.toString());
382         }
383         Object result = IntrospectionUtils.callMethodN(target, methodName,
384                 paramValues, paramTypes);
385         processMethodCallResult(result);
386     }
387
388
389     /**
390      * Clean up after parsing is complete.
391      */

392     @Override
393     public void finish() throws Exception {
394         bodyText = null;
395     }
396
397
398     /**
399      * Subclasses may override this method to perform additional processing of the
400      * invoked method's result.
401      *
402      * @param result the Object returned by the method invoked, possibly null
403      */

404     protected void processMethodCallResult(Object result) {
405         // do nothing
406     }
407
408
409     /**
410      * Render a printable version of this Rule.
411      */

412     @Override
413     public String toString() {
414         StringBuilder sb = new StringBuilder("CallMethodRule[");
415         sb.append("methodName=");
416         sb.append(methodName);
417         sb.append(", paramCount=");
418         sb.append(paramCount);
419         sb.append(", paramTypes={");
420         if (paramTypes != null) {
421             for (int i = 0; i < paramTypes.length; i++) {
422                 if (i > 0) {
423                     sb.append(", ");
424                 }
425                 sb.append(paramTypes[i].getName());
426             }
427         }
428         sb.append("}");
429         sb.append("]");
430         return sb.toString();
431     }
432 }