001package org.unix4j.variable;
002
003import java.util.LinkedHashMap;
004import java.util.Map;
005
006/**
007 * Simple variable resolver implementation backed by a map of variable names to
008 * values. The variable name is a key in the backing name-to-value map
009 * (including the dollar sign of the variable name). If a map is already
010 * available and the variable names can be derived from the map keys,
011 * {@link MapVariableResolver} may be the better alternative.
012 */
013public class SimpleVariableResolver implements VariableResolver {
014
015        private final Map<String, Object> nameToValue = new LinkedHashMap<String, Object>();
016
017        /**
018         * Sets the specified value for the variable with the given name. If the
019         * value is null, the variable is cleared. Returns the old value held by the
020         * value before setting it, or null if no such variable existed.
021         * 
022         * @param name
023         *            the variable name
024         * @param value
025         *            the new value for the variable, null to clear the variable
026         * @return the old value held by the variable before setting it, or null if
027         *         the variable did not exist before
028         */
029        public Object setValue(String name, Object value) {
030                if (value != null) {
031                        return nameToValue.put(name, value);
032                }
033                return nameToValue.remove(name);
034        }
035
036        @Override
037        public Object getValue(String name) {
038                return nameToValue.get(name);
039        }
040
041        @Override
042        public String toString() {
043                return nameToValue.toString();
044        }
045
046}