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.scxml2.env.xpath;
018
019import org.apache.commons.jxpath.Variables;
020import org.apache.commons.scxml2.Context;
021import org.apache.commons.scxml2.env.SimpleContext;
022
023/**
024 * A {@link Context} implementation for JXPath environments.
025 *
026 */
027public class XPathContext extends SimpleContext
028implements Context, Variables {
029
030    /** Serial version UID. */
031    private static final long serialVersionUID = -6803159294612685806L;
032
033    /**
034     * No argument constructor.
035     *
036     */
037    public XPathContext() {
038        super();
039    }
040
041    /**
042     * Constructor for cascading contexts.
043     *
044     * @param parent The parent context. Can be null.
045     */
046    public XPathContext(final Context parent) {
047        super(parent);
048    }
049
050    @Override
051    public boolean isDeclaredVariable(final String varName) {
052        return has(varName);
053    }
054
055    @Override
056    public Object getVariable(final String varName) {
057        return get(varName);
058    }
059
060    @Override
061    public void declareVariable(final String varName, final Object value) {
062        set(varName, value);
063    }
064
065    @Override
066    public void undeclareVariable(final String varName) {
067        if (has(varName)) {
068            Context ctx = this;
069            while (!ctx.hasLocal(varName)) {
070                ctx = ctx.getParent();
071                if (ctx == null) {
072                    return;
073                }
074            }
075            ctx.getVars().remove(varName);
076        }
077    }
078}