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.Pointer;
21  import org.apache.commons.jxpath.ri.EvalContext;
22  import org.apache.commons.jxpath.ri.compiler.NodeTest;
23  import org.apache.commons.jxpath.ri.model.NodePointer;
24  
25  /**
26   * EvalContext that returns the current node from the parent context if the test succeeds.
27   */
28  public class SelfContext extends EvalContext {
29  
30      private final NodeTest nodeTest;
31      private boolean startedSet;
32      private NodePointer nodePointer;
33  
34      /**
35       * Constructs a new SelfContext.
36       *
37       * @param parentContext EvalContext
38       * @param nodeTest      guard
39       */
40      public SelfContext(final EvalContext parentContext, final NodeTest nodeTest) {
41          super(parentContext);
42          this.nodeTest = nodeTest;
43      }
44  
45      @Override
46      public NodePointer getCurrentNodePointer() {
47          if (position == 0 && !setPosition(1)) {
48              return null;
49          }
50          return nodePointer;
51      }
52  
53      @Override
54      public Pointer getSingleNodePointer() {
55          return parentContext.getSingleNodePointer();
56      }
57  
58      @Override
59      public boolean nextNode() {
60          return setPosition(getCurrentPosition() + 1);
61      }
62  
63      @Override
64      public void reset() {
65          super.reset();
66          startedSet = false;
67      }
68  
69      @Override
70      public boolean setPosition(final int position) {
71          if (position != 1) {
72              return false;
73          }
74          super.setPosition(position);
75          if (!startedSet) {
76              startedSet = true;
77              nodePointer = parentContext.getCurrentNodePointer();
78          }
79          if (nodePointer == null) {
80              return false;
81          }
82          return nodeTest == null || nodePointer.testNode(nodeTest);
83      }
84  }