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.groovy;
018
019import groovy.lang.Binding;
020import groovy.lang.MissingPropertyException;
021
022import java.io.Serializable;
023import java.util.LinkedHashMap;
024import java.util.Map;
025
026/**
027 * Delegating Groovy Binding class which delegates all variables access to its GroovyContext
028 */
029public class GroovyContextBinding extends Binding implements Serializable {
030
031    private static final long serialVersionUID = 1L;
032
033    private GroovyContext context;
034
035    public GroovyContextBinding(GroovyContext context) {
036        if (context == null) {
037            throw new IllegalArgumentException("Parameter context may not be null");
038        }
039        this.context = context;
040    }
041
042    GroovyContext getContext() {
043        return context;
044    }
045
046    @Override
047    public Object getVariable(String name) {
048        Object result = context.get(name);
049        if (result == null && !context.has(name)) {
050            throw new MissingPropertyException(name, this.getClass());
051        }
052        return result;
053    }
054
055    @Override
056    public void setVariable(String name, Object value) {
057        if (context.has(name)) {
058            context.set(name, value);
059        } else {
060            context.setLocal(name, value);
061        }
062    }
063
064    @Override
065    public boolean hasVariable(String name) {
066        return context.has(name);
067    }
068
069    @Override
070    public Map<String, Object> getVariables() {
071        return new LinkedHashMap<String, Object>(context.getVars());
072    }
073
074    @Override
075    public Object getProperty(String property) {
076        return getVariable(property);
077    }
078
079    @Override
080    public void setProperty(String property, Object newValue) {
081        setVariable(property, newValue);
082    }
083}