001package org.unix4j.variable;
002
003import java.util.Map;
004
005/**
006 * Variable resolver based on an existing map, where the keys may or may not be
007 * prefixed with the variable dollar sign '$'. This class is very similar to
008 * {@link SimpleVariableResolver} but it is used when a map with name/value for
009 * the variables exists already, possibly with a slightly different key (for
010 * instance without the dollar prefix). Subclasses may want to override the
011 * {@link #getMapKeyForVariableName(String)} method to change the default
012 * assumption about the map keys.
013 */
014public class MapVariableResolver implements VariableResolver {
015
016        private final Map<?, ?> nameToValue;
017
018        /**
019         * Constructor with name-to-value map.
020         * 
021         * @param nameToValue
022         *            the map with variable names as keys
023         */
024        public MapVariableResolver(Map<?, ?> nameToValue) {
025                this.nameToValue = nameToValue;
026        }
027
028        /**
029         * Returns a variable resolver for the ENV variables.
030         * 
031         * @return a variable resolver for the ENV variables.
032         * @see System#getenv()
033         */
034        public static MapVariableResolver getEnv() {
035                return new MapVariableResolver(System.getenv());
036        }
037
038        /**
039         * Returns a variable resolver for the system properties.
040         * 
041         * @return a variable resolver for the system properties
042         * @see System#getProperties()
043         */
044        public static MapVariableResolver getSystemProperties() {
045                return new MapVariableResolver(System.getProperties());
046        }
047
048        /**
049         * Returns the map key for a given variable name. If the variable name
050         * starts with a dollar sign '$', the name without dollar prefix is
051         * returned. Otherwise, the variable name is returned unchanged.
052         * 
053         * @param variableName
054         *            the variable name, usually prefixed with a dollar sign '$'
055         * @return the variable name without dollar prefix
056         */
057        public String getMapKeyForVariableName(String variableName) {
058                if (variableName.startsWith("$")) {
059                        return variableName.substring(1);
060                }
061                return variableName;
062        }
063
064        @Override
065        public Object getValue(String name) {
066                final String key = getMapKeyForVariableName(name);
067                return nameToValue.get(key);
068        }
069
070        @Override
071        public String toString() {
072                return nameToValue.toString();
073        }
074
075}