    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.NodeSet;
    021import org.apache.commons.jxpath.ri.EvalContext;
    022import org.apache.commons.jxpath.ri.model.NodePointer;
    023
    024/**
    025 * A simple context that is based on a {@link NodeSet}.
    026 */
    027public class NodeSetContext extends EvalContext {
    028
    029    private boolean startedSet;
    030    private final NodeSet nodeSet;
    031
    032    /**
    033     * Constructs a new NodeSetContext.
    034     *
    035     * @param parentContext parent context
    036     * @param nodeSet       associated NodeSet
    037     */
    038    public NodeSetContext(final EvalContext parentContext, final NodeSet nodeSet) {
    039        super(parentContext);
    040        this.nodeSet = nodeSet;
    041    }
    042
    043    @Override
    044    public NodePointer getCurrentNodePointer() {
    045        if (position == 0 && !setPosition(1)) {
    046            return null;
    047        }
    048        return (NodePointer) nodeSet.getPointers().get(position - 1);
    049    }
    050
    051    @Override
    052    public NodeSet getNodeSet() {
    053        return nodeSet;
    054    }
    055
    056    @Override
    057    public boolean nextNode() {
    058        return setPosition(position + 1);
    059    }
    060
    061    @Override
    062    public boolean nextSet() {
    063        if (startedSet) {
    064            return false;
    065        }
    066        startedSet = true;
    067        return true;
    068    }
    069
    070    @Override
    071    public boolean setPosition(final int position) {
    072        super.setPosition(position);
    073        return position >= 1 && position <= nodeSet.getPointers().size();
    074    }
    075}