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 */
017
018package org.apache.commons.jxpath.ri.axes;
019
020import org.apache.commons.jxpath.Pointer;
021import org.apache.commons.jxpath.ri.EvalContext;
022import org.apache.commons.jxpath.ri.model.NodePointer;
023
024/**
025 * A single-set EvalContext that provides access to the current node of the parent context and nothing else. It does not pass the iteration on to the parent
026 * context.
027 */
028public class InitialContext extends EvalContext {
029
030    private boolean started;
031    private boolean collection;
032    private final NodePointer nodePointer;
033
034    /**
035     * Constructs a new InitialContext.
036     *
037     * @param parentContext parent context
038     */
039    public InitialContext(final EvalContext parentContext) {
040        super(parentContext);
041        nodePointer = (NodePointer) parentContext.getCurrentNodePointer().clone();
042        if (nodePointer != null) {
043            collection = nodePointer.getIndex() == NodePointer.WHOLE_COLLECTION;
044        }
045    }
046
047    @Override
048    public NodePointer getCurrentNodePointer() {
049        return nodePointer;
050    }
051
052    @Override
053    public Pointer getSingleNodePointer() {
054        return nodePointer;
055    }
056
057    @Override
058    public Object getValue() {
059        return nodePointer.getValue();
060    }
061
062    @Override
063    public boolean nextNode() {
064        return setPosition(position + 1);
065    }
066
067    @Override
068    public boolean nextSet() {
069        if (started) {
070            return false;
071        }
072        started = true;
073        return true;
074    }
075
076    @Override
077    public boolean setPosition(final int position) {
078        this.position = position;
079        if (collection) {
080            if (position >= 1 && position <= nodePointer.getLength()) {
081                nodePointer.setIndex(position - 1);
082                return true;
083            }
084            return false;
085        }
086        return position == 1;
087    }
088}