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