1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jxpath.ri.compiler;
18
19 import java.util.Arrays;
20
21 import org.apache.commons.jxpath.Function;
22 import org.apache.commons.jxpath.JXPathFunctionNotFoundException;
23 import org.apache.commons.jxpath.NodeSet;
24 import org.apache.commons.jxpath.ri.EvalContext;
25 import org.apache.commons.jxpath.ri.QName;
26 import org.apache.commons.jxpath.ri.axes.NodeSetContext;
27
28
29
30
31
32
33
34
35 public class ExtensionFunction extends Operation {
36
37 private QName functionName;
38
39
40
41
42
43
44 public ExtensionFunction(QName functionName, Expression[] args) {
45 super(args);
46 this.functionName = functionName;
47 }
48
49
50
51
52
53 public QName getFunctionName() {
54 return functionName;
55 }
56
57
58
59
60
61
62 public boolean computeContextDependent() {
63 return true;
64 }
65
66 public String toString() {
67 StringBuffer buffer = new StringBuffer();
68 buffer.append(functionName);
69 buffer.append('(');
70 Expression[] args = getArguments();
71 if (args != null) {
72 for (int i = 0; i < args.length; i++) {
73 if (i > 0) {
74 buffer.append(", ");
75 }
76 buffer.append(args[i]);
77 }
78 }
79 buffer.append(')');
80 return buffer.toString();
81 }
82
83 public Object compute(EvalContext context) {
84 return computeValue(context);
85 }
86
87 public Object computeValue(EvalContext context) {
88 Object[] parameters = null;
89 if (args != null) {
90 parameters = new Object[args.length];
91 for (int i = 0; i < args.length; i++) {
92 parameters[i] = convert(args[i].compute(context));
93 }
94 }
95
96 Function function =
97 context.getRootContext().getFunction(functionName, parameters);
98 if (function == null) {
99 throw new JXPathFunctionNotFoundException("No such function: "
100 + functionName + Arrays.asList(parameters));
101 }
102 Object result = function.invoke(context, parameters);
103 return result instanceof NodeSet ? new NodeSetContext(context,
104 (NodeSet) result) : result;
105 }
106
107
108
109
110
111
112 private Object convert(Object object) {
113 return object instanceof EvalContext ? ((EvalContext) object).getValue() : object;
114 }
115 }