001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.jxpath.ri.axes;
018
019import org.apache.commons.jxpath.Pointer;
020import org.apache.commons.jxpath.ri.EvalContext;
021import org.apache.commons.jxpath.ri.compiler.NodeTest;
022import org.apache.commons.jxpath.ri.model.NodePointer;
023
024/**
025 * EvalContext that returns the current node from the parent context if the
026 * test succeeds.
027 *
028 * @author Dmitri Plotnikov
029 * @version $Revision: 1523199 $ $Date: 2013-09-14 11:45:47 +0200 (Sa, 14 Sep 2013) $
030 */
031public class SelfContext extends EvalContext {
032    private NodeTest nodeTest;
033    private boolean startedSet = false;
034    private NodePointer nodePointer;
035
036    /**
037     * Create a new SelfContext.
038     * @param parentContext EvalContext
039     * @param nodeTest guard
040     */
041    public SelfContext(EvalContext parentContext, NodeTest nodeTest) {
042        super(parentContext);
043        this.nodeTest = nodeTest;
044    }
045
046    public Pointer getSingleNodePointer() {
047        return parentContext.getSingleNodePointer();
048    }
049
050    public NodePointer getCurrentNodePointer() {
051        if (position == 0 && !setPosition(1)) {
052            return null;
053        }
054        return nodePointer;
055    }
056
057    public boolean nextNode() {
058        return setPosition(getCurrentPosition() + 1);
059    }
060
061    public void reset() {
062        super.reset();
063        startedSet = false;
064    }
065
066    public boolean setPosition(int position) {
067        if (position != 1) {
068            return false;
069        }
070        super.setPosition(position);
071        if (!startedSet) {
072            startedSet = true;
073            nodePointer = parentContext.getCurrentNodePointer();
074        }
075
076        if (nodePointer == null) {
077            return false;
078        }
079
080        return nodeTest == null || nodePointer.testNode(nodeTest);
081    }
082}