001package org.unix4j.variable;
002
003import java.util.Deque;
004import java.util.LinkedList;
005
006import org.unix4j.convert.ValueConverter;
007
008/**
009 * Default implementation of {@link VariableContext}.
010 */
011public class DefaultVariableContext implements VariableContext {
012        
013        private final Deque<VariableResolver> resolvers = new LinkedList<VariableResolver>();
014
015        @Override
016        public void addVariableResolver(VariableResolver resolver) {
017                resolvers.addFirst(resolver);
018        }
019        @Override
020        public void removeVariableResolver(VariableResolver resolver) {
021                resolvers.removeFirstOccurrence(resolver);
022        }
023        @Override
024        public Object getValue(String name) {
025                for (final VariableResolver resolver : resolvers) {
026                        final Object value = resolver.getValue(name);
027                        if (value != null) {
028                                return value;
029                        }
030                }
031                return null;
032        }
033
034        @Override
035        public <V> V getValue(String name, ValueConverter<V> converter) throws IllegalArgumentException {
036                final Object value = getValue(name);
037                if (value == null) {
038                        return null;
039                }
040                final V converted = converter.convert(value);
041                if (converted == null) {
042                        //conversion failed, throw exception
043                        throw new IllegalArgumentException("value conversion not supported for variable " + name + "=" + value + " using converter=" + converter);
044                }
045                return converted;
046        }
047        
048        @Override
049        public String toString() {
050                return getClass().getSimpleName() + resolvers;
051        }
052
053}