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   * @version $Id: StrLookup.java 1654144 2015-01-23 08:47:00Z britter $
38   */
39  public abstract class StrLookup<V> {
40  
41      /**
42       * Lookup that always returns null.
43       */
44      private static final StrLookup<String> NONE_LOOKUP = new MapStrLookup<String>(null);
45  
46      //-----------------------------------------------------------------------
47      /**
48       * Returns a lookup which always returns null.
49       *
50       * @return a lookup that always returns null, not null
51       */
52      public static StrLookup<?> noneLookup() {
53          return NONE_LOOKUP;
54      }
55  
56      /**
57       * Creates a copy of the given properties instance.
58       * 
59       * @param input the Properties instance to copy.
60       * @return a copy of {@code input}.
61       */
62      private static Properties copyProperties(Properties input) {
63          if (input == null) {
64              return null;
65          }
66  
67          Properties output = new Properties();
68          @SuppressWarnings("unchecked") // Property names are Strings.
69          Enumeration<String> propertyNames = (Enumeration<String>) input.propertyNames();
70  
71          while (propertyNames.hasMoreElements()) {
72              String propertyName = propertyNames.nextElement();
73              output.setProperty(propertyName, input.getProperty(propertyName));
74          }
75  
76          return output;
77      }
78  
79      /**
80       * Returns a new lookup which uses a copy of the current
81       * {@link System#getProperties() System properties}.
82       * <p>
83       * If a security manager blocked access to system properties, then null will
84       * be returned from every lookup.
85       * <p>
86       * If a null key is used, this lookup will throw a NullPointerException.
87       *
88       * @return a lookup using system properties, not null
89       */
90      public static StrLookup<String> systemPropertiesLookup() {
91          Properties systemProperties = null;
92  
93          try {
94              systemProperties = System.getProperties();
95          } catch (final SecurityException ex) {
96              // Squelched.  All lookup(String) will return null.
97          }
98  
99          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 }