View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3.text;
18  
19  import java.util.Enumeration;
20  import java.util.Map;
21  import java.util.Properties;
22  
23  /**
24   * Lookup a String key to a String value.
25   * <p>
26   * This class represents the simplest form of a string to string map.
27   * It has a benefit over a map in that it can create the result on
28   * demand based on the key.
29   * <p>
30   * This class comes complete with various factory methods.
31   * If these do not suffice, you can subclass and implement your own matcher.
32   * <p>
33   * For example, it would be possible to implement a lookup that used the
34   * key as a primary key, and looked up the value on demand from the database
35   *
36   * @since 2.2
37   */
38  public abstract class StrLookup<V> {
39  
40      /**
41       * Lookup that always returns null.
42       */
43      private static final StrLookup<String> NONE_LOOKUP = new MapStrLookup<String>(null);
44  
45      //-----------------------------------------------------------------------
46      /**
47       * Returns a lookup which always returns null.
48       *
49       * @return a lookup that always returns null, not null
50       */
51      public static StrLookup<?> noneLookup() {
52          return NONE_LOOKUP;
53      }
54  
55      /**
56       * Creates a copy of the given properties instance.
57       * 
58       * @param input the Properties instance to copy.
59       * @return a copy of {@code input}.
60       */
61      private static Properties copyProperties(Properties input) {
62          if (input == null) {
63              return null;
64          }
65  
66          Properties output = new Properties();
67          @SuppressWarnings("unchecked") // Property names are Strings.
68          Enumeration<String> propertyNames = (Enumeration<String>) input.propertyNames();
69  
70          while (propertyNames.hasMoreElements()) {
71              String propertyName = propertyNames.nextElement();
72              output.setProperty(propertyName, input.getProperty(propertyName));
73          }
74  
75          return output;
76      }
77  
78      /**
79       * Returns a new lookup which uses a copy of the current
80       * {@link System#getProperties() System properties}.
81       * <p>
82       * If a security manager blocked access to system properties, then null will
83       * be returned from every lookup.
84       * <p>
85       * If a null key is used, this lookup will throw a NullPointerException.
86       *
87       * @return a lookup using system properties, not null
88       */
89      public static StrLookup<String> systemPropertiesLookup() {
90          Properties systemProperties = null;
91  
92          try {
93              systemProperties = System.getProperties();
94          } catch (final SecurityException ex) {
95              // Squelched.  All lookup(String) will return null.
96          }
97  
98          Properties properties = copyProperties(systemProperties);
99          @SuppressWarnings("unchecked") // System property keys and values are always Strings
100         final Map<String, String> propertiesMap = (Map) properties;
101 
102         return new MapStrLookup<String>(propertiesMap);
103     }
104 
105     /**
106      * Returns a lookup which looks up values using a map.
107      * <p>
108      * If the map is null, then null will be returned from every lookup.
109      * The map result object is converted to a string using toString().
110      *
111      * @param <V> the type of the values supported by the lookup
112      * @param map  the map of keys to values, may be null
113      * @return a lookup using the map, not null
114      */
115     public static <V> StrLookup<V> mapLookup(final Map<String, V> map) {
116         return new MapStrLookup<V>(map);
117     }
118 
119     //-----------------------------------------------------------------------
120     /**
121      * Constructor.
122      */
123     protected StrLookup() {
124         super();
125     }
126 
127     /**
128      * Looks up a String key to a String value.
129      * <p>
130      * The internal implementation may use any mechanism to return the value.
131      * The simplest implementation is to use a Map. However, virtually any
132      * implementation is possible.
133      * <p>
134      * For example, it would be possible to implement a lookup that used the
135      * key as a primary key, and looked up the value on demand from the database
136      * Or, a numeric based implementation could be created that treats the key
137      * as an integer, increments the value and return the result as a string -
138      * converting 1 to 2, 15 to 16 etc.
139      * <p>
140      * The {@link #lookup(String)} method always returns a String, regardless of
141      * the underlying data, by converting it as necessary. For example:
142      * <pre>
143      * Map&lt;String, Object&gt; map = new HashMap&lt;String, Object&gt;();
144      * map.put("number", Integer.valueOf(2));
145      * assertEquals("2", StrLookup.mapLookup(map).lookup("number"));
146      * </pre>
147      * @param key  the key to be looked up, may be null
148      * @return the matching value, null if no match
149      */
150     public abstract String lookup(String key);
151 
152     //-----------------------------------------------------------------------
153     /**
154      * Lookup implementation that uses a Map.
155      */
156     static class MapStrLookup<V> extends StrLookup<V> {
157 
158         /** Map keys are variable names and value. */
159         private final Map<String, V> map;
160 
161         /**
162          * Creates a new instance backed by a Map.
163          *
164          * @param map  the map of keys to values, may be null
165          */
166         MapStrLookup(final Map<String, V> map) {
167             this.map = map;
168         }
169 
170         /**
171          * Looks up a String key to a String value using the map.
172          * <p>
173          * If the map is null, then null is returned.
174          * The map result object is converted to a string using toString().
175          *
176          * @param key  the key to be looked up, may be null
177          * @return the matching value, null if no match
178          */
179         @Override
180         public String lookup(final String key) {
181             if (map == null) {
182                 return null;
183             }
184             final Object obj = map.get(key);
185             if (obj == null) {
186                 return null;
187             }
188             return obj.toString();
189         }
190     }
191 }