1. /* $Id: CallMethodRule.java,v 1.35 2004/05/10 06:30:06 skitching Exp $
  2. *
  3. * Copyright 2001-2004 The Apache Software Foundation.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * 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.commons.digester;
  18. import org.apache.commons.beanutils.ConvertUtils;
  19. import org.apache.commons.beanutils.MethodUtils;
  20. import org.xml.sax.Attributes;
  21. /**
  22. * <p>Rule implementation that calls a method on an object on the stack
  23. * (normally the top/parent object), passing arguments collected from
  24. * subsequent <code>CallParamRule</code> rules or from the body of this
  25. * element. </p>
  26. *
  27. * <p>By using {@link #CallMethodRule(String methodName)}
  28. * a method call can be made to a method which accepts no
  29. * arguments.</p>
  30. *
  31. * <p>Incompatible method parameter types are converted
  32. * using <code>org.apache.commons.beanutils.ConvertUtils</code>.
  33. * </p>
  34. *
  35. * <p>This rule now uses {@link MethodUtils#invokeMethod} by default.
  36. * This increases the kinds of methods successfully and allows primitives
  37. * to be matched by passing in wrapper classes.
  38. * There are rare cases when {@link MethodUtils#invokeExactMethod}
  39. * (the old defualt) is required.
  40. * This method is much stricter in it's reflection.
  41. * Setting the <code>UseExactMatch</code> to true reverts to the use of this
  42. * method.</p>
  43. *
  44. * <p>Note that the target method is invoked when the <i>end</i> of
  45. * the tag the CallMethodRule fired on is encountered, <i>not</i> when the
  46. * last parameter becomes available. This implies that rules which fire on
  47. * tags nested within the one associated with the CallMethodRule will
  48. * fire before the CallMethodRule invokes the target method. This behaviour is
  49. * not configurable. </p>
  50. *
  51. * <p>Note also that if a CallMethodRule is expecting exactly one parameter
  52. * and that parameter is not available (eg CallParamRule is used with an
  53. * attribute name but the attribute does not exist) then the method will
  54. * not be invoked. If a CallMethodRule is expecting more than one parameter,
  55. * then it is always invoked, regardless of whether the parameters were
  56. * available or not (missing parameters are passed as null values).</p>
  57. */
  58. public class CallMethodRule extends Rule {
  59. // ----------------------------------------------------------- Constructors
  60. /**
  61. * Construct a "call method" rule with the specified method name. The
  62. * parameter types (if any) default to java.lang.String.
  63. *
  64. * @param digester The associated Digester
  65. * @param methodName Method name of the parent method to call
  66. * @param paramCount The number of parameters to collect, or
  67. * zero for a single argument from the body of this element.
  68. *
  69. *
  70. * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
  71. * Use {@link #CallMethodRule(String methodName,int paramCount)} instead.
  72. */
  73. public CallMethodRule(Digester digester, String methodName,
  74. int paramCount) {
  75. this(methodName, paramCount);
  76. }
  77. /**
  78. * Construct a "call method" rule with the specified method name.
  79. *
  80. * @param digester The associated Digester
  81. * @param methodName Method name of the parent method to call
  82. * @param paramCount The number of parameters to collect, or
  83. * zero for a single argument from the body of ths element
  84. * @param paramTypes The Java class names of the arguments
  85. * (if you wish to use a primitive type, specify the corresonding
  86. * Java wrapper class instead, such as <code>java.lang.Boolean</code>
  87. * for a <code>boolean</code> parameter)
  88. *
  89. * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
  90. * Use {@link #CallMethodRule(String methodName,int paramCount, String [] paramTypes)} instead.
  91. */
  92. public CallMethodRule(Digester digester, String methodName,
  93. int paramCount, String paramTypes[]) {
  94. this(methodName, paramCount, paramTypes);
  95. }
  96. /**
  97. * Construct a "call method" rule with the specified method name.
  98. *
  99. * @param digester The associated Digester
  100. * @param methodName Method name of the parent method to call
  101. * @param paramCount The number of parameters to collect, or
  102. * zero for a single argument from the body of ths element
  103. * @param paramTypes The Java classes that represent the
  104. * parameter types of the method arguments
  105. * (if you wish to use a primitive type, specify the corresonding
  106. * Java wrapper class instead, such as <code>java.lang.Boolean.TYPE</code>
  107. * for a <code>boolean</code> parameter)
  108. *
  109. * @deprecated The digester instance is now set in the {@link Digester#addRule} method.
  110. * Use {@link #CallMethodRule(String methodName,int paramCount, Class [] paramTypes)} instead.
  111. */
  112. public CallMethodRule(Digester digester, String methodName,
  113. int paramCount, Class paramTypes[]) {
  114. this(methodName, paramCount, paramTypes);
  115. }
  116. /**
  117. * Construct a "call method" rule with the specified method name. The
  118. * parameter types (if any) default to java.lang.String.
  119. *
  120. * @param methodName Method name of the parent method to call
  121. * @param paramCount The number of parameters to collect, or
  122. * zero for a single argument from the body of this element.
  123. */
  124. public CallMethodRule(String methodName,
  125. int paramCount) {
  126. this(0, methodName, paramCount);
  127. }
  128. /**
  129. * Construct a "call method" rule with the specified method name. The
  130. * parameter types (if any) default to java.lang.String.
  131. *
  132. * @param targetOffset location of the target object. Positive numbers are
  133. * relative to the top of the digester object stack. Negative numbers
  134. * are relative to the bottom of the stack. Zero implies the top
  135. * object on the stack.
  136. * @param methodName Method name of the parent method to call
  137. * @param paramCount The number of parameters to collect, or
  138. * zero for a single argument from the body of this element.
  139. */
  140. public CallMethodRule(int targetOffset,
  141. String methodName,
  142. int paramCount) {
  143. this.targetOffset = targetOffset;
  144. this.methodName = methodName;
  145. this.paramCount = paramCount;
  146. if (paramCount == 0) {
  147. this.paramTypes = new Class[] { String.class };
  148. } else {
  149. this.paramTypes = new Class[paramCount];
  150. for (int i = 0; i < this.paramTypes.length; i++) {
  151. this.paramTypes[i] = String.class;
  152. }
  153. }
  154. }
  155. /**
  156. * Construct a "call method" rule with the specified method name.
  157. * The method should accept no parameters.
  158. *
  159. * @param methodName Method name of the parent method to call
  160. */
  161. public CallMethodRule(String methodName) {
  162. this(0, methodName, 0, (Class[]) null);
  163. }
  164. /**
  165. * Construct a "call method" rule with the specified method name.
  166. * The method should accept no parameters.
  167. *
  168. * @param targetOffset location of the target object. Positive numbers are
  169. * relative to the top of the digester object stack. Negative numbers
  170. * are relative to the bottom of the stack. Zero implies the top
  171. * object on the stack.
  172. * @param methodName Method name of the parent method to call
  173. */
  174. public CallMethodRule(int targetOffset, String methodName) {
  175. this(targetOffset, methodName, 0, (Class[]) null);
  176. }
  177. /**
  178. * Construct a "call method" rule with the specified method name and
  179. * parameter types. If <code>paramCount</code> is set to zero the rule
  180. * will use the body of this element as the single argument of the
  181. * method, unless <code>paramTypes</code> is null or empty, in this
  182. * case the rule will call the specified method with no arguments.
  183. *
  184. * @param methodName Method name of the parent method to call
  185. * @param paramCount The number of parameters to collect, or
  186. * zero for a single argument from the body of ths element
  187. * @param paramTypes The Java class names of the arguments
  188. * (if you wish to use a primitive type, specify the corresonding
  189. * Java wrapper class instead, such as <code>java.lang.Boolean</code>
  190. * for a <code>boolean</code> parameter)
  191. */
  192. public CallMethodRule(
  193. String methodName,
  194. int paramCount,
  195. String paramTypes[]) {
  196. this(0, methodName, paramCount, paramTypes);
  197. }
  198. /**
  199. * Construct a "call method" rule with the specified method name and
  200. * parameter types. If <code>paramCount</code> is set to zero the rule
  201. * will use the body of this element as the single argument of the
  202. * method, unless <code>paramTypes</code> is null or empty, in this
  203. * case the rule will call the specified method with no arguments.
  204. *
  205. * @param targetOffset location of the target object. Positive numbers are
  206. * relative to the top of the digester object stack. Negative numbers
  207. * are relative to the bottom of the stack. Zero implies the top
  208. * object on the stack.
  209. * @param methodName Method name of the parent method to call
  210. * @param paramCount The number of parameters to collect, or
  211. * zero for a single argument from the body of ths element
  212. * @param paramTypes The Java class names of the arguments
  213. * (if you wish to use a primitive type, specify the corresonding
  214. * Java wrapper class instead, such as <code>java.lang.Boolean</code>
  215. * for a <code>boolean</code> parameter)
  216. */
  217. public CallMethodRule( int targetOffset,
  218. String methodName,
  219. int paramCount,
  220. String paramTypes[]) {
  221. this.targetOffset = targetOffset;
  222. this.methodName = methodName;
  223. this.paramCount = paramCount;
  224. if (paramTypes == null) {
  225. this.paramTypes = new Class[paramCount];
  226. for (int i = 0; i < this.paramTypes.length; i++) {
  227. this.paramTypes[i] = "abc".getClass();
  228. }
  229. } else {
  230. // copy the parameter class names into an array
  231. // the classes will be loaded when the digester is set
  232. this.paramClassNames = new String[paramTypes.length];
  233. for (int i = 0; i < this.paramClassNames.length; i++) {
  234. this.paramClassNames[i] = paramTypes[i];
  235. }
  236. }
  237. }
  238. /**
  239. * Construct a "call method" rule with the specified method name and
  240. * parameter types. If <code>paramCount</code> is set to zero the rule
  241. * will use the body of this element as the single argument of the
  242. * method, unless <code>paramTypes</code> is null or empty, in this
  243. * case the rule will call the specified method with no arguments.
  244. *
  245. * @param methodName Method name of the parent method to call
  246. * @param paramCount The number of parameters to collect, or
  247. * zero for a single argument from the body of ths element
  248. * @param paramTypes The Java classes that represent the
  249. * parameter types of the method arguments
  250. * (if you wish to use a primitive type, specify the corresonding
  251. * Java wrapper class instead, such as <code>java.lang.Boolean.TYPE</code>
  252. * for a <code>boolean</code> parameter)
  253. */
  254. public CallMethodRule(
  255. String methodName,
  256. int paramCount,
  257. Class paramTypes[]) {
  258. this(0, methodName, paramCount, paramTypes);
  259. }
  260. /**
  261. * Construct a "call method" rule with the specified method name and
  262. * parameter types. If <code>paramCount</code> is set to zero the rule
  263. * will use the body of this element as the single argument of the
  264. * method, unless <code>paramTypes</code> is null or empty, in this
  265. * case the rule will call the specified method with no arguments.
  266. *
  267. * @param targetOffset location of the target object. Positive numbers are
  268. * relative to the top of the digester object stack. Negative numbers
  269. * are relative to the bottom of the stack. Zero implies the top
  270. * object on the stack.
  271. * @param methodName Method name of the parent method to call
  272. * @param paramCount The number of parameters to collect, or
  273. * zero for a single argument from the body of ths element
  274. * @param paramTypes The Java classes that represent the
  275. * parameter types of the method arguments
  276. * (if you wish to use a primitive type, specify the corresonding
  277. * Java wrapper class instead, such as <code>java.lang.Boolean.TYPE</code>
  278. * for a <code>boolean</code> parameter)
  279. */
  280. public CallMethodRule( int targetOffset,
  281. String methodName,
  282. int paramCount,
  283. Class paramTypes[]) {
  284. this.targetOffset = targetOffset;
  285. this.methodName = methodName;
  286. this.paramCount = paramCount;
  287. if (paramTypes == null) {
  288. this.paramTypes = new Class[paramCount];
  289. for (int i = 0; i < this.paramTypes.length; i++) {
  290. this.paramTypes[i] = "abc".getClass();
  291. }
  292. } else {
  293. this.paramTypes = new Class[paramTypes.length];
  294. for (int i = 0; i < this.paramTypes.length; i++) {
  295. this.paramTypes[i] = paramTypes[i];
  296. }
  297. }
  298. }
  299. // ----------------------------------------------------- Instance Variables
  300. /**
  301. * The body text collected from this element.
  302. */
  303. protected String bodyText = null;
  304. /**
  305. * location of the target object for the call, relative to the
  306. * top of the digester object stack. The default value of zero
  307. * means the target object is the one on top of the stack.
  308. */
  309. private int targetOffset = 0;
  310. /**
  311. * The method name to call on the parent object.
  312. */
  313. protected String methodName = null;
  314. /**
  315. * The number of parameters to collect from <code>MethodParam</code> rules.
  316. * If this value is zero, a single parameter will be collected from the
  317. * body of this element.
  318. */
  319. protected int paramCount = 0;
  320. /**
  321. * The parameter types of the parameters to be collected.
  322. */
  323. protected Class paramTypes[] = null;
  324. /**
  325. * The names of the classes of the parameters to be collected.
  326. * This attribute allows creation of the classes to be postponed until the digester is set.
  327. */
  328. private String paramClassNames[] = null;
  329. /**
  330. * Should <code>MethodUtils.invokeExactMethod</code> be used for reflection.
  331. */
  332. protected boolean useExactMatch = false;
  333. // --------------------------------------------------------- Public Methods
  334. /**
  335. * Should <code>MethodUtils.invokeExactMethod</code>
  336. * be used for the reflection.
  337. */
  338. public boolean getUseExactMatch() {
  339. return useExactMatch;
  340. }
  341. /**
  342. * Set whether <code>MethodUtils.invokeExactMethod</code>
  343. * should be used for the reflection.
  344. */
  345. public void setUseExactMatch(boolean useExactMatch)
  346. {
  347. this.useExactMatch = useExactMatch;
  348. }
  349. /**
  350. * Set the associated digester.
  351. * If needed, this class loads the parameter classes from their names.
  352. */
  353. public void setDigester(Digester digester)
  354. {
  355. // call superclass
  356. super.setDigester(digester);
  357. // if necessary, load parameter classes
  358. if (this.paramClassNames != null) {
  359. this.paramTypes = new Class[paramClassNames.length];
  360. for (int i = 0; i < this.paramClassNames.length; i++) {
  361. try {
  362. this.paramTypes[i] =
  363. digester.getClassLoader().loadClass(this.paramClassNames[i]);
  364. } catch (ClassNotFoundException e) {
  365. // use the digester log
  366. digester.getLogger().error("(CallMethodRule) Cannot load class " + this.paramClassNames[i], e);
  367. this.paramTypes[i] = null; // Will cause NPE later
  368. }
  369. }
  370. }
  371. }
  372. /**
  373. * Process the start of this element.
  374. *
  375. * @param attributes The attribute list for this element
  376. */
  377. public void begin(Attributes attributes) throws Exception {
  378. // Push an array to capture the parameter values if necessary
  379. if (paramCount > 0) {
  380. Object parameters[] = new Object[paramCount];
  381. for (int i = 0; i < parameters.length; i++) {
  382. parameters[i] = null;
  383. }
  384. digester.pushParams(parameters);
  385. }
  386. }
  387. /**
  388. * Process the body text of this element.
  389. *
  390. * @param bodyText The body text of this element
  391. */
  392. public void body(String bodyText) throws Exception {
  393. if (paramCount == 0) {
  394. this.bodyText = bodyText.trim();
  395. }
  396. }
  397. /**
  398. * Process the end of this element.
  399. */
  400. public void end() throws Exception {
  401. // Retrieve or construct the parameter values array
  402. Object parameters[] = null;
  403. if (paramCount > 0) {
  404. parameters = (Object[]) digester.popParams();
  405. if (digester.log.isTraceEnabled()) {
  406. for (int i=0,size=parameters.length;i<size;i++) {
  407. digester.log.trace("[CallMethodRule](" + i + ")" + parameters[i]) ;
  408. }
  409. }
  410. // In the case where the parameter for the method
  411. // is taken from an attribute, and that attribute
  412. // isn't actually defined in the source XML file,
  413. // skip the method call
  414. if (paramCount == 1 && parameters[0] == null) {
  415. return;
  416. }
  417. } else if (paramTypes != null && paramTypes.length != 0) {
  418. // In the case where the parameter for the method
  419. // is taken from the body text, but there is no
  420. // body text included in the source XML file,
  421. // skip the method call
  422. if (bodyText == null) {
  423. return;
  424. }
  425. parameters = new Object[1];
  426. parameters[0] = bodyText;
  427. if (paramTypes.length == 0) {
  428. paramTypes = new Class[1];
  429. paramTypes[0] = "abc".getClass();
  430. }
  431. }
  432. // Construct the parameter values array we will need
  433. // We only do the conversion if the param value is a String and
  434. // the specified paramType is not String.
  435. Object paramValues[] = new Object[paramTypes.length];
  436. for (int i = 0; i < paramTypes.length; i++) {
  437. // convert nulls and convert stringy parameters
  438. // for non-stringy param types
  439. if(
  440. parameters[i] == null ||
  441. (parameters[i] instanceof String &&
  442. !String.class.isAssignableFrom(paramTypes[i]))) {
  443. paramValues[i] =
  444. ConvertUtils.convert((String) parameters[i], paramTypes[i]);
  445. } else {
  446. paramValues[i] = parameters[i];
  447. }
  448. }
  449. // Determine the target object for the method call
  450. Object target;
  451. if (targetOffset >= 0) {
  452. target = digester.peek(targetOffset);
  453. } else {
  454. target = digester.peek( digester.getCount() + targetOffset );
  455. }
  456. if (target == null) {
  457. StringBuffer sb = new StringBuffer();
  458. sb.append("[CallMethodRule]{");
  459. sb.append(digester.match);
  460. sb.append("} Call target is null (");
  461. sb.append("targetOffset=");
  462. sb.append(targetOffset);
  463. sb.append(",stackdepth=");
  464. sb.append(digester.getCount());
  465. sb.append(")");
  466. throw new org.xml.sax.SAXException(sb.toString());
  467. }
  468. // Invoke the required method on the top object
  469. if (digester.log.isDebugEnabled()) {
  470. StringBuffer sb = new StringBuffer("[CallMethodRule]{");
  471. sb.append(digester.match);
  472. sb.append("} Call ");
  473. sb.append(target.getClass().getName());
  474. sb.append(".");
  475. sb.append(methodName);
  476. sb.append("(");
  477. for (int i = 0; i < paramValues.length; i++) {
  478. if (i > 0) {
  479. sb.append(",");
  480. }
  481. if (paramValues[i] == null) {
  482. sb.append("null");
  483. } else {
  484. sb.append(paramValues[i].toString());
  485. }
  486. sb.append("/");
  487. if (paramTypes[i] == null) {
  488. sb.append("null");
  489. } else {
  490. sb.append(paramTypes[i].getName());
  491. }
  492. }
  493. sb.append(")");
  494. digester.log.debug(sb.toString());
  495. }
  496. Object result = null;
  497. if (useExactMatch) {
  498. // invoke using exact match
  499. result = MethodUtils.invokeExactMethod(target, methodName,
  500. paramValues, paramTypes);
  501. } else {
  502. // invoke using fuzzier match
  503. result = MethodUtils.invokeMethod(target, methodName,
  504. paramValues, paramTypes);
  505. }
  506. processMethodCallResult(result);
  507. }
  508. /**
  509. * Clean up after parsing is complete.
  510. */
  511. public void finish() throws Exception {
  512. bodyText = null;
  513. }
  514. /**
  515. * Subclasses may override this method to perform additional processing of the
  516. * invoked method's result.
  517. *
  518. * @param result the Object returned by the method invoked, possibly null
  519. */
  520. protected void processMethodCallResult(Object result) {
  521. // do nothing
  522. }
  523. /**
  524. * Render a printable version of this Rule.
  525. */
  526. public String toString() {
  527. StringBuffer sb = new StringBuffer("CallMethodRule[");
  528. sb.append("methodName=");
  529. sb.append(methodName);
  530. sb.append(", paramCount=");
  531. sb.append(paramCount);
  532. sb.append(", paramTypes={");
  533. if (paramTypes != null) {
  534. for (int i = 0; i < paramTypes.length; i++) {
  535. if (i > 0) {
  536. sb.append(", ");
  537. }
  538. sb.append(paramTypes[i].getName());
  539. }
  540. }
  541. sb.append("}");
  542. sb.append("]");
  543. return (sb.toString());
  544. }
  545. }