1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.jxpath.ri.axes;
19
20 import java.util.ArrayList;
21 import java.util.Iterator;
22
23 import org.apache.commons.jxpath.BasicNodeSet;
24 import org.apache.commons.jxpath.ri.EvalContext;
25 import org.apache.commons.jxpath.ri.model.NodePointer;
26
27 /**
28 * EvalContext that represents a union between other contexts - result of a union operation like (a | b)
29 */
30 public class UnionContext extends NodeSetContext {
31
32 private final EvalContext[] contexts;
33 private boolean prepared;
34
35 /**
36 * Constructs a new UnionContext.
37 *
38 * @param parentContext parent context
39 * @param contexts child contexts
40 */
41 public UnionContext(final EvalContext parentContext, final EvalContext[] contexts) {
42 super(parentContext, new BasicNodeSet());
43 this.contexts = contexts;
44 }
45
46 @Override
47 public int getDocumentOrder() {
48 return contexts.length > 1 ? 1 : super.getDocumentOrder();
49 }
50
51 @Override
52 public boolean setPosition(final int position) {
53 if (!prepared) {
54 prepared = true;
55 final BasicNodeSet nodeSet = (BasicNodeSet) getNodeSet();
56 final ArrayList<NodePointer> pointers = new ArrayList<>();
57 for (final EvalContext ctx : contexts) {
58 while (ctx.nextSet()) {
59 while (ctx.nextNode()) {
60 final NodePointer ptr = ctx.getCurrentNodePointer();
61 if (!pointers.contains(ptr)) {
62 pointers.add(ptr);
63 }
64 }
65 }
66 }
67 sortPointers(pointers);
68 for (final Iterator<NodePointer> it = pointers.iterator(); it.hasNext();) {
69 nodeSet.add(it.next());
70 }
71 }
72 return super.setPosition(position);
73 }
74 }