    1   /*
    2    * Copyright 1999-2004 The Apache Software Foundation
    3    *
    4    * Licensed under the Apache License, Version 2.0 (the "License");
    5    * you may not use this file except in compliance with the License.
    6    * You may obtain a copy of the License at
    7    *
    8    *     http://www.apache.org/licenses/LICENSE-2.0
    9    *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  package org.apache.commons.jxpath.ri.axes;
    17
    18  import java.util.HashSet;
    19
    20  import org.apache.commons.jxpath.BasicNodeSet;
    21  import org.apache.commons.jxpath.ri.EvalContext;
    22  import org.apache.commons.jxpath.ri.model.NodePointer;
    23
    24  /***
    25   * EvalContext that represents a union between other contexts - result
    26   * of a union operation like (a | b)
    27   *
    28   * @author Dmitri Plotnikov
    29   * @version $Revision: 1.12 $ $Date: 2004/02/29 14:17:38 $
    30   */
    31  public class UnionContext extends NodeSetContext {
    32      private boolean startedSet = false;
    33      private EvalContext contexts[];
    34      private boolean prepared = false;
    35
    36      public UnionContext(EvalContext parentContext, EvalContext contexts[]) {
    37          super(parentContext, new BasicNodeSet());
    38          this.contexts = contexts;
    39      }
    40
    41      public int getDocumentOrder() {
    42          if (contexts.length > 1) {
    43              return 1;
    44          }
    45          return super.getDocumentOrder();
    46      }
    47
    48      public boolean setPosition(int position) {
    49          if (!prepared) {
    50              prepared = true;
    51              BasicNodeSet nodeSet = (BasicNodeSet) getNodeSet();
    52              HashSet set = new HashSet();
    53              for (int i = 0; i < contexts.length; i++) {
    54                  EvalContext ctx = (EvalContext) contexts[i];
    55                  while (ctx.nextSet()) {
    56                      while (ctx.nextNode()) {
    57                          NodePointer ptr = ctx.getCurrentNodePointer();
    58                          if (!set.contains(ptr)) {
    59                              nodeSet.add(ptr);
    60                              set.add(ptr);
    61                          }
    62                      }
    63                  }
    64              }
    65          }
    66          return super.setPosition(position);
    67      }
    68  }