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.model.NodePointer;
022
023/**
024 * A single-set EvalContext that provides access to the current node of
025 * the parent context and nothing else.  It does not pass the iteration
026 * on to the parent context.
027 *
028 * @author Dmitri Plotnikov
029 * @version $Revision: 652845 $ $Date: 2008-05-02 19:46:46 +0200 (Fr, 02 Mai 2008) $
030 */
031public class InitialContext extends EvalContext {
032    private boolean started = false;
033    private boolean collection;
034    private NodePointer nodePointer;
035
036    /**
037     * Create a new InitialContext.
038     * @param parentContext parent context
039     */
040    public InitialContext(EvalContext parentContext) {
041        super(parentContext);
042        nodePointer =
043            (NodePointer) parentContext.getCurrentNodePointer().clone();
044        if (nodePointer != null) {
045            collection =
046                (nodePointer.getIndex() == NodePointer.WHOLE_COLLECTION);
047        }
048    }
049
050    public Pointer getSingleNodePointer() {
051        return nodePointer;
052    }
053
054    public NodePointer getCurrentNodePointer() {
055        return nodePointer;
056    }
057
058    public Object getValue() {
059        return nodePointer.getValue();
060    }
061
062    public boolean nextNode() {
063        return setPosition(position + 1);
064    }
065
066    public boolean setPosition(int position) {
067        this.position = position;
068        if (collection) {
069            if (position >= 1 && position <= nodePointer.getLength()) {
070                nodePointer.setIndex(position - 1);
071                return true;
072            }
073            return false;
074        }
075        return position == 1;
076    }
077
078    public boolean nextSet() {
079        if (started) {
080            return false;
081        }
082        started = true;
083        return true;
084    }
085}