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; 018 019import java.io.Serializable; 020import java.util.AbstractMap; 021import java.util.HashSet; 022import java.util.Set; 023 024import org.apache.commons.scxml2.Context; 025 026/** 027 * A map that will back the effective {@link Context} for an {@link org.apache.commons.scxml2.Evaluator} execution. 028 * The effective context enables the chaining of contexts all the way from the current state node to the root. 029 */ 030public final class EffectiveContextMap extends AbstractMap<String, Object> implements Serializable { 031 032 private static final long serialVersionUID = 1L; 033 034 /** The {@link org.apache.commons.scxml2.Context} for the current state. */ 035 private final Context leaf; 036 037 /** Constructor. */ 038 public EffectiveContextMap(final Context ctx) { 039 super(); 040 this.leaf = ctx; 041 } 042 043 /** 044 * {@inheritDoc} 045 */ 046 @Override 047 public Set<Entry<String, Object>> entrySet() { 048 Set<Entry<String, Object>> entrySet = new HashSet<Entry<String, Object>>(); 049 Context current = leaf; 050 while (current != null) { 051 entrySet.addAll(current.getVars().entrySet()); 052 current = current.getParent(); 053 } 054 return entrySet; 055 } 056 057 /** 058 * {@inheritDoc} 059 */ 060 @Override 061 public Object put(final String key, final Object value) { 062 Object old = leaf.get(key); 063 if (leaf.has(key)) { 064 leaf.set(key, value); 065 } else { 066 leaf.setLocal(key, value); 067 } 068 return old; 069 } 070 071 /** 072 * {@inheritDoc} 073 */ 074 @Override 075 public Object get(final Object key) { 076 if (key != null) { 077 Context current = leaf; 078 while (current != null) { 079 if (current.getVars().containsKey(key.toString())) { 080 return current.getVars().get(key); 081 } 082 current = current.getParent(); 083 } 084 } 085 return null; 086 } 087}