1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.apache.commons.jxpath.ri.compiler;
  17. import java.util.Arrays;
  18. import org.apache.commons.jxpath.Function;
  19. import org.apache.commons.jxpath.JXPathException;
  20. import org.apache.commons.jxpath.ri.EvalContext;
  21. import org.apache.commons.jxpath.ri.QName;
  22. /**
  23. * Represents an element of the parse tree representing an extension function
  24. * call.
  25. *
  26. * @author Dmitri Plotnikov
  27. * @version $Revision: 1.13 $ $Date: 2004/03/25 05:42:01 $
  28. */
  29. public class ExtensionFunction extends Operation {
  30. private QName functionName;
  31. public ExtensionFunction(QName functionName, Expression args[]) {
  32. super(args);
  33. this.functionName = functionName;
  34. }
  35. public QName getFunctionName() {
  36. return functionName;
  37. }
  38. /**
  39. * An extension function gets the current context, therefore it MAY be
  40. * context dependent.
  41. */
  42. public boolean computeContextDependent() {
  43. return true;
  44. }
  45. public String toString() {
  46. StringBuffer buffer = new StringBuffer();
  47. buffer.append(functionName);
  48. buffer.append('(');
  49. Expression args[] = getArguments();
  50. if (args != null) {
  51. for (int i = 0; i < args.length; i++) {
  52. if (i > 0) {
  53. buffer.append(", ");
  54. }
  55. buffer.append(args[i]);
  56. }
  57. }
  58. buffer.append(')');
  59. return buffer.toString();
  60. }
  61. public Object compute(EvalContext context) {
  62. return computeValue(context);
  63. }
  64. public Object computeValue(EvalContext context) {
  65. Object[] parameters = null;
  66. if (args != null) {
  67. parameters = new Object[args.length];
  68. for (int i = 0; i < args.length; i++) {
  69. parameters[i] = convert(args[i].compute(context));
  70. }
  71. }
  72. Function function =
  73. context.getRootContext().getFunction(functionName, parameters);
  74. if (function == null) {
  75. throw new JXPathException(
  76. "No such function: "
  77. + functionName
  78. + Arrays.asList(parameters));
  79. }
  80. return function.invoke(context, parameters);
  81. }
  82. private Object convert(Object object) {
  83. if (object instanceof EvalContext) {
  84. return ((EvalContext) object).getValue();
  85. }
  86. return object;
  87. }
  88. }