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