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. import org.apache.commons.jxpath.ri.EvalContext;
  18. import org.apache.commons.jxpath.ri.compiler.NodeTest;
  19. import org.apache.commons.jxpath.ri.model.NodePointer;
  20. /**
  21. * EvalContext that walks the "ancestor::" and "ancestor-or-self::" axes.
  22. *
  23. * @author Dmitri Plotnikov
  24. * @version $Revision: 1.15 $ $Date: 2004/03/25 03:49:50 $
  25. */
  26. public class AncestorContext extends EvalContext {
  27. private NodeTest nodeTest;
  28. private boolean setStarted = false;
  29. private NodePointer currentNodePointer;
  30. private boolean includeSelf;
  31. /**
  32. * @param parentContext represents the previous step on the path
  33. * @param includeSelf differentiates between "ancestor::" and "ancestor-
  34. * or-self::" axes
  35. * @param nameTest is the name of the element(s) we are looking for
  36. */
  37. public AncestorContext(
  38. EvalContext parentContext,
  39. boolean includeSelf,
  40. NodeTest nodeTest)
  41. {
  42. super(parentContext);
  43. this.includeSelf = includeSelf;
  44. this.nodeTest = nodeTest;
  45. }
  46. public NodePointer getCurrentNodePointer() {
  47. return currentNodePointer;
  48. }
  49. public int getDocumentOrder() {
  50. return -1;
  51. }
  52. public void reset() {
  53. super.reset();
  54. setStarted = false;
  55. }
  56. public boolean setPosition(int position) {
  57. if (position < getCurrentPosition()) {
  58. reset();
  59. }
  60. while (getCurrentPosition() < position) {
  61. if (!nextNode()) {
  62. return false;
  63. }
  64. }
  65. return true;
  66. }
  67. public boolean nextNode() {
  68. if (!setStarted) {
  69. setStarted = true;
  70. currentNodePointer = parentContext.getCurrentNodePointer();
  71. if (includeSelf) {
  72. if (currentNodePointer.testNode(nodeTest)) {
  73. position++;
  74. return true;
  75. }
  76. }
  77. }
  78. while (true) {
  79. currentNodePointer = currentNodePointer.getImmediateParentPointer();
  80. if (currentNodePointer == null) {
  81. return false;
  82. }
  83. if (currentNodePointer.testNode(nodeTest)) {
  84. position++;
  85. return true;
  86. }
  87. }
  88. }
  89. }