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.lang3.text;
018
019import java.util.Enumeration;
020import java.util.Map;
021import java.util.Properties;
022
023/**
024 * Lookup a String key to a String value.
025 * <p>
026 * This class represents the simplest form of a string to string map.
027 * It has a benefit over a map in that it can create the result on
028 * demand based on the key.
029 * <p>
030 * This class comes complete with various factory methods.
031 * If these do not suffice, you can subclass and implement your own matcher.
032 * <p>
033 * For example, it would be possible to implement a lookup that used the
034 * key as a primary key, and looked up the value on demand from the database
035 *
036 * @since 2.2
037 * @version $Id: StrLookup.java 1654144 2015-01-23 08:47:00Z britter $
038 */
039public abstract class StrLookup<V> {
040
041    /**
042     * Lookup that always returns null.
043     */
044    private static final StrLookup<String> NONE_LOOKUP = new MapStrLookup<String>(null);
045
046    //-----------------------------------------------------------------------
047    /**
048     * Returns a lookup which always returns null.
049     *
050     * @return a lookup that always returns null, not null
051     */
052    public static StrLookup<?> noneLookup() {
053        return NONE_LOOKUP;
054    }
055
056    /**
057     * Creates a copy of the given properties instance.
058     * 
059     * @param input the Properties instance to copy.
060     * @return a copy of {@code input}.
061     */
062    private static Properties copyProperties(Properties input) {
063        if (input == null) {
064            return null;
065        }
066
067        Properties output = new Properties();
068        @SuppressWarnings("unchecked") // Property names are Strings.
069        Enumeration<String> propertyNames = (Enumeration<String>) input.propertyNames();
070
071        while (propertyNames.hasMoreElements()) {
072            String propertyName = propertyNames.nextElement();
073            output.setProperty(propertyName, input.getProperty(propertyName));
074        }
075
076        return output;
077    }
078
079    /**
080     * Returns a new lookup which uses a copy of the current
081     * {@link System#getProperties() System properties}.
082     * <p>
083     * If a security manager blocked access to system properties, then null will
084     * be returned from every lookup.
085     * <p>
086     * If a null key is used, this lookup will throw a NullPointerException.
087     *
088     * @return a lookup using system properties, not null
089     */
090    public static StrLookup<String> systemPropertiesLookup() {
091        Properties systemProperties = null;
092
093        try {
094            systemProperties = System.getProperties();
095        } catch (final SecurityException ex) {
096            // Squelched.  All lookup(String) will return null.
097        }
098
099        Properties properties = copyProperties(systemProperties);
100        @SuppressWarnings("unchecked") // System property keys and values are always Strings
101        final Map<String, String> propertiesMap = (Map) properties;
102
103        return new MapStrLookup<String>(propertiesMap);
104    }
105
106    /**
107     * Returns a lookup which looks up values using a map.
108     * <p>
109     * If the map is null, then null will be returned from every lookup.
110     * The map result object is converted to a string using toString().
111     *
112     * @param <V> the type of the values supported by the lookup
113     * @param map  the map of keys to values, may be null
114     * @return a lookup using the map, not null
115     */
116    public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
117        return new MapStrLookup<V>(map);
118    }
119
120    //-----------------------------------------------------------------------
121    /**
122     * Constructor.
123     */
124    protected StrLookup() {
125        super();
126    }
127
128    /**
129     * Looks up a String key to a String value.
130     * <p>
131     * The internal implementation may use any mechanism to return the value.
132     * The simplest implementation is to use a Map. However, virtually any
133     * implementation is possible.
134     * <p>
135     * For example, it would be possible to implement a lookup that used the
136     * key as a primary key, and looked up the value on demand from the database
137     * Or, a numeric based implementation could be created that treats the key
138     * as an integer, increments the value and return the result as a string -
139     * converting 1 to 2, 15 to 16 etc.
140     * <p>
141     * The {@link #lookup(String)} method always returns a String, regardless of
142     * the underlying data, by converting it as necessary. For example:
143     * <pre>
144     * Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
145     * map.put("number", Integer.valueOf(2));
146     * assertEquals("2", StrLookup.mapLookup(map).lookup("number"));
147     * </pre>
148     * @param key  the key to be looked up, may be null
149     * @return the matching value, null if no match
150     */
151    public abstract String lookup(String key);
152
153    //-----------------------------------------------------------------------
154    /**
155     * Lookup implementation that uses a Map.
156     */
157    static class MapStrLookup<V> extends StrLookup<V> {
158
159        /** Map keys are variable names and value. */
160        private final Map<String, V> map;
161
162        /**
163         * Creates a new instance backed by a Map.
164         *
165         * @param map  the map of keys to values, may be null
166         */
167        MapStrLookup(final Map<String, V> map) {
168            this.map = map;
169        }
170
171        /**
172         * Looks up a String key to a String value using the map.
173         * <p>
174         * If the map is null, then null is returned.
175         * The map result object is converted to a string using toString().
176         *
177         * @param key  the key to be looked up, may be null
178         * @return the matching value, null if no match
179         */
180        @Override
181        public String lookup(final String key) {
182            if (map == null) {
183                return null;
184            }
185            final Object obj = map.get(key);
186            if (obj == null) {
187                return null;
188            }
189            return obj.toString();
190        }
191    }
192}