View Javadoc
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 org.apache.commons.jxpath.NodeSet;
21  import org.apache.commons.jxpath.ri.EvalContext;
22  import org.apache.commons.jxpath.ri.model.NodePointer;
23  
24  /**
25   * A simple context that is based on a {@link NodeSet}.
26   */
27  public class NodeSetContext extends EvalContext {
28  
29      private boolean startedSet;
30      private final NodeSet nodeSet;
31  
32      /**
33       * Constructs a new NodeSetContext.
34       *
35       * @param parentContext parent context
36       * @param nodeSet       associated NodeSet
37       */
38      public NodeSetContext(final EvalContext parentContext, final NodeSet nodeSet) {
39          super(parentContext);
40          this.nodeSet = nodeSet;
41      }
42  
43      @Override
44      public NodePointer getCurrentNodePointer() {
45          if (position == 0 && !setPosition(1)) {
46              return null;
47          }
48          return (NodePointer) nodeSet.getPointers().get(position - 1);
49      }
50  
51      @Override
52      public NodeSet getNodeSet() {
53          return nodeSet;
54      }
55  
56      @Override
57      public boolean nextNode() {
58          return setPosition(position + 1);
59      }
60  
61      @Override
62      public boolean nextSet() {
63          if (startedSet) {
64              return false;
65          }
66          startedSet = true;
67          return true;
68      }
69  
70      @Override
71      public boolean setPosition(final int position) {
72          super.setPosition(position);
73          return position >= 1 && position <= nodeSet.getPointers().size();
74      }
75  }