Debian Codegraph @

net/sf/saxon/expr/sort/GroupByIterator.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr.sort;
9
10 import com.saxonica.ee.stream.ManualGroupIterator;
11 import net.sf.saxon.expr.Expression;
12 import net.sf.saxon.expr.LastPositionFinder;
13 import net.sf.saxon.expr.XPathContext;
14 import net.sf.saxon.lib.StringCollator;
15 import net.sf.saxon.om.*;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.tree.iter.ListIterator;
18 import net.sf.saxon.tree.iter.LookaheadIterator;
19 import net.sf.saxon.value.AtomicValue;
20
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.List;
24
25 /**
26 * A GroupByIterator iterates over a sequence of groups defined by
27 * xsl:for-each-group group-by="x". The groups are returned in
28 * order of first appearance. Note that an item can appear in several groups;
29 * indeed, an item may be the leading item of more than one group, which means
30 * that knowing the leading item is not enough to know the current group.
31 * <p>The GroupByIterator acts as a SequenceIterator, where successive calls of
32 * next() return the leading item of each group in turn. The current item of
33 * the iterator is therefore the leading item of the current group. To get access
34 * to all the members of the current group, the method iterateCurrentGroup() is used;
35 * this underpins the current-group() function in XSLT. The grouping key for the
36 * current group is available via the getCurrentGroupingKey() method.</p>
37 */
38
39 public class GroupByIterator implements GroupIterator, LastPositionFinder, LookaheadIterator<Item<?>> {
40
41 // The implementation of group-by is not pipelined. All the items in the population
42 // are read at the start, their grouping keys are calculated, and the groups are formed
43 // in memory as a hash table indexed by the grouping key. This hash table is then
44 // flattened into three parallel lists: a list of groups (each group being represented
45 // as a list of items in population order), a list of grouping keys, and a list of
46 // the initial items of the groups.
47
48 private SequenceIterator<?> population;
49 protected Expression keyExpression;
50 private StringCollator collator;
51 private XPathContext keyContext;
52 private int position = 0;
53
54 // Main data structure holds one entry for each group. The entry is also an ArrayList,
55 // which contains the Items that are members of the group, in population order.
56 // The groups are arranged in order of first appearance within the population.
57 protected List<List<Item<?>>> groups = new ArrayList<>(40);
58
59 // This parallel structure identifies the grouping key for each group. The list
60 // corresponds one-to-one with the list of groups.
61 protected List<AtomicSequence> groupKeys = new ArrayList<>(40);
62
63 // An AtomicComparer is used to do the comparisons of individual atomic values
64 //protected AtomicComparer comparer;
65
66 protected boolean composite;
67
68 /**
69 * Create a GroupByIterator
70 *
71 * @param population iterator over the population to be grouped
72 * @param keyExpression the expression used to calculate the grouping key
73 * @param keyContext dynamic context for calculating the grouping key
74 * @param collator Collation to be used for comparing grouping keys
75 * @param composite true if grouping keys are to be treated as composite keys
76 * @throws XPathException if an error occurs
77 */
78
79 public GroupByIterator(SequenceIterator<?> population, Expression keyExpression,
80 XPathContext keyContext, StringCollator collator, boolean composite)
81 throws XPathException {
82 this.population = population;
83 this.keyExpression = keyExpression;
84 this.keyContext = keyContext;
85 this.collator = collator;
86 this.composite = composite;
87 if (composite) {
88 buildIndexedGroupsComposite();
89 } else {
90 buildIndexedGroups();
91 }
92 }
93
94 public GroupByIterator() {
95 }
96
97 /**
98 * Build the grouping table forming groups of items with equal keys.
99 * This form of grouping allows a member of the population to be present in zero
100 * or more groups, one for each value of the grouping key.
101 *
102 * @throws XPathException if any error occurs
103 */
104
105 private void buildIndexedGroups() throws XPathException {
106 HashMap<AtomicMatchKey, List<Item<?>>> index = new HashMap<>(40);
107 XPathContext c2 = keyContext.newMinorContext();
108 FocusIterator focus = c2.trackFocus(population);
109 int implicitTimezone = c2.getImplicitTimezone();
110 Item item;
111 while ((item = focus.next()) != null) {
112 SequenceIterator keys = keyExpression.iterate(c2);
113 boolean firstKey = true;
114 while (true) {
115 AtomicValue key = (AtomicValue) keys.next();
116 if (key == null) {
117 break;
118 }
119 AtomicMatchKey comparisonKey;
120 if (key.isNaN()) {
121 comparisonKey = AtomicMatchKey.NaN_MATCH_KEY;
122 } else {
123 comparisonKey = key.getXPathComparable(false, collator, implicitTimezone);
124 }
125 List<Item<?>> g = index.get(comparisonKey);
126 if (g == null) {
127 List<Item<?>> newGroup = new ArrayList<>(20);
128 newGroup.add(item);
129 groups.add(newGroup);
130 groupKeys.add(key);
131 index.put(comparisonKey, newGroup);
132 } else {
133 if (firstKey) {
134 g.add(item);
135 } else {
136 // if this is not the first key value for this item, we
137 // check whether the item is already in this group before
138 // adding it again. If it is in this group, then we know
139 // it will be at the end.
140 if (g.get(g.size() - 1) != item) {
141 g.add(item);
142 }
143 }
144 }
145 firstKey = false;
146 }
147
148 }
149 }
150
151 /**
152 * Build the grouping table forming groups of items with equal keys.
153 * This form of grouping allows the grouping key to be a sequence of atomic values.
154 *
155 * @throws XPathException if any error occurs
156 */
157
158 private void buildIndexedGroupsComposite() throws XPathException {
159 HashMap<List<AtomicMatchKey>, List<Item<?>>> index = new HashMap<>(40);
160 XPathContext c2 = keyContext.newMinorContext();
161 FocusIterator focus = c2.trackFocus(population);
162 int implicitTimezone = c2.getImplicitTimezone();
163 Item item;
164 while ((item = focus.next()) != null) {
165 SequenceIterator keys = keyExpression.iterate(c2);
166 List<AtomicMatchKey> ckList = new ArrayList<>();
167 List<AtomicValue> compositeKey = new ArrayList<>();
168 while (true) {
169 AtomicValue key = (AtomicValue) keys.next();
170 if (key == null) {
171 break;
172 }
173 compositeKey.add(key);
174 AtomicMatchKey comparisonKey;
175 if (key.isNaN()) {
176 comparisonKey = AtomicMatchKey.NaN_MATCH_KEY;
177 } else {
178 comparisonKey = key.getXPathComparable(false, collator, implicitTimezone);
179 }
180 ckList.add(comparisonKey);
181 }
182
183 List<Item<?>> g = index.get(ckList);
184 if (g == null) {
185 List<Item<?>> newGroup = new ArrayList<>(20);
186 newGroup.add(item);
187 groups.add(newGroup);
188 groupKeys.add(new AtomicArray(compositeKey));
189 index.put(ckList, newGroup);
190 } else {
191 g.add(item);
192 }
193 }
194 }
195
196
197 /**
198 * Get the value of the grouping key for the current group
199 *
200 * @return the grouping key
201 */
202
203 public synchronized AtomicSequence getCurrentGroupingKey() {
204 AtomicSequence val = groupKeys.get(position - 1);
205 if (val == null) {
206 return EmptyAtomicSequence.getInstance();
207 } else {
208 return val;
209 }
210 }
211
212 /**
213 * Get an iterator over the items in the current group
214 *
215 * @return the iterator
216 */
217
218 public SequenceIterator<?> iterateCurrentGroup() {
219 return new ListIterator<>(groups.get(position - 1));
220 }
221
222 /**
223 * Get the contents of the current group as a java List
224 *
225 * @return the contents of the current group
226 */
227
228 public List getCurrentGroup() {
229 return groups.get(position - 1);
230 }
231
232 public boolean hasNext() {
233 return position < groups.size();
234 }
235
236 /*@Nullable*/
237 public Item next() throws XPathException {
238 if (position >= 0 && position < groups.size()) {
239 position++;
240 return current();
241 } else {
242 position = -1;
243 return null;
244 }
245 }
246
247 private Item current() {
248 if (position < 1) {
249 return null;
250 }
251 // return the initial item of the current group
252 return groups.get(position - 1).get(0);
253 }
254
255 public void close() {
256 }
257
258 /**
259 * Get properties of this iterator, as a bit-significant integer.
260 *
261 * @return the properties of this iterator. This will be some combination of
262 * properties such as {@link #GROUNDED}, {@link #LAST_POSITION_FINDER},
263 * and {@link #LOOKAHEAD}. It is always
264 * acceptable to return the value zero, indicating that there are no known special properties.
265 * It is acceptable for the properties of the iterator to change depending on its state.
266 */
267
268 public int getProperties() {
269 return LAST_POSITION_FINDER | LOOKAHEAD;
270 }
271
272 /**
273 * Get the last position (that is, the number of groups)
274 */
275
276 public int getLength() throws XPathException {
277 return groups.size();
278 }
279
280 //#if EE==true
281
282 public ManualGroupIterator getSnapShot(XPathContext context) {
283 return new ManualGroupByIterator();
284 }
285
286 public class ManualGroupByIterator extends ManualGroupIterator {
287
288 List<Item<?>> currentGroup = groups.get(position - 1);
289 AtomicSequence currentGroupingKey = groupKeys.get(position - 1);
290
291 public ManualGroupByIterator() {
292 super(groups.get(position - 1).get(0), position);
293 setLastPositionFinder(() -> groups.size());
294 }
295
296 public SequenceIterator<Item<?>> iterateCurrentGroup() {
297 return new ListIterator<>(currentGroup);
298 }
299
300 public AtomicSequence getCurrentGroupingKey() {
301 return currentGroupingKey;
302 }
303
304
305 @Override
306 public int getLength() throws XPathException {
307 return groups.size();
308 }
309
310
311 }
312 //#endif
313
314
315 }
316