View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.scxml2.env.groovy;
18  
19  import groovy.lang.Binding;
20  import groovy.lang.MissingPropertyException;
21  
22  import java.io.Serializable;
23  import java.util.LinkedHashMap;
24  import java.util.Map;
25  
26  /**
27   * Delegating Groovy Binding class which delegates all variables access to its GroovyContext
28   */
29  public class GroovyContextBinding extends Binding implements Serializable {
30  
31      private static final long serialVersionUID = 1L;
32  
33      private GroovyContext context;
34  
35      public GroovyContextBinding(GroovyContext context) {
36          if (context == null) {
37              throw new IllegalArgumentException("Parameter context may not be null");
38          }
39          this.context = context;
40      }
41  
42      GroovyContext getContext() {
43          return context;
44      }
45  
46      @Override
47      public Object getVariable(String name) {
48          Object result = context.get(name);
49          if (result == null && !context.has(name)) {
50              throw new MissingPropertyException(name, this.getClass());
51          }
52          return result;
53      }
54  
55      @Override
56      public void setVariable(String name, Object value) {
57          if (context.has(name)) {
58              context.set(name, value);
59          } else {
60              context.setLocal(name, value);
61          }
62      }
63  
64      @Override
65      public boolean hasVariable(String name) {
66          return context.has(name);
67      }
68  
69      @Override
70      public Map<String, Object> getVariables() {
71          return new LinkedHashMap<String, Object>(context.getVars());
72      }
73  
74      @Override
75      public Object getProperty(String property) {
76          return getVariable(property);
77      }
78  
79      @Override
80      public void setProperty(String property, Object newValue) {
81          setVariable(property, newValue);
82      }
83  }