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