1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 package org.jaxen.function;
50
51 import java.util.Iterator;
52 import java.util.List;
53
54 import org.jaxen.Context;
55 import org.jaxen.Function;
56 import org.jaxen.FunctionCallException;
57 import org.jaxen.Navigator;
58
59 /***
60 * <p><b>4.4</b> <code><i>number</i> sum(<i>node-set</i>)</code> </p>
61 *
62 * <blockquote src="http://www.w3.org/TR/xpath#function-sum">
63 * The sum function returns the sum, for each node in the argument node-set,
64 * of the result of converting the string-values of the node to a number.
65 * </blockquote>
66 *
67 * @author bob mcwhirter (bob @ werken.com)
68 * @see <a href="http://www.w3.org/TR/xpath#function-sum" target="_top">Section 4.4 of the XPath Specification</a>
69 */
70 public class SumFunction implements Function
71 {
72
73 /***
74 * Create a new <code>SumFunction</code> object.
75 */
76 public SumFunction() {}
77
78 /*** Returns the sum of its arguments.
79 *
80 * @param context the context at the point in the
81 * expression when the function is called
82 * @param args a list that contains exactly one item, also a <code>List</code>
83 *
84 * @return a <code>Double</code> containing the sum of the items in <code>args.get(0)</code>
85 *
86 * @throws FunctionCallException if <code>args</code> has more or less than one item;
87 * or if the first argument is not a <code>List</code>
88 */
89 public Object call(Context context,
90 List args) throws FunctionCallException
91 {
92
93 if (args.size() == 1)
94 {
95 return evaluate( args.get(0),
96 context.getNavigator() );
97 }
98
99 throw new FunctionCallException( "sum() requires one argument." );
100 }
101
102 /***
103 * Returns the sum of the items in a list.
104 * If necessary, each item in the list is first converted to a <code>Double</code>
105 * as if by the XPath <code>number()</code> function.
106 *
107 * @param obj a <code>List</code> of numbers to be summed
108 * @param nav ignored
109 *
110 * @return the sum of the list
111 *
112 * @throws FunctionCallException if <code>obj</code> is not a <code>List</code>
113 */
114 public static Double evaluate(Object obj,
115 Navigator nav) throws FunctionCallException
116 {
117 double sum = 0;
118
119 if (obj instanceof List)
120 {
121 Iterator nodeIter = ((List)obj).iterator();
122 while ( nodeIter.hasNext() )
123 {
124 double term = NumberFunction.evaluate( nodeIter.next(),
125 nav ).doubleValue();
126 sum += term;
127 }
128 }
129 else
130 {
131 throw new FunctionCallException("The argument to the sum function must be a node-set");
132 }
133
134 return new Double(sum);
135 }
136
137 }