001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.conf;
020
021import java.io.BufferedInputStream;
022import java.io.DataInput;
023import java.io.DataOutput;
024import java.io.File;
025import java.io.FileInputStream;
026import java.io.IOException;
027import java.io.InputStream;
028import java.io.InputStreamReader;
029import java.io.OutputStream;
030import java.io.OutputStreamWriter;
031import java.io.Reader;
032import java.io.Writer;
033import java.lang.ref.WeakReference;
034import java.net.InetSocketAddress;
035import java.net.URL;
036import java.util.ArrayList;
037import java.util.Arrays;
038import java.util.Collection;
039import java.util.Collections;
040import java.util.Enumeration;
041import java.util.HashMap;
042import java.util.HashSet;
043import java.util.Iterator;
044import java.util.LinkedList;
045import java.util.List;
046import java.util.ListIterator;
047import java.util.Map;
048import java.util.Map.Entry;
049import java.util.Properties;
050import java.util.Set;
051import java.util.StringTokenizer;
052import java.util.WeakHashMap;
053import java.util.concurrent.CopyOnWriteArrayList;
054import java.util.regex.Matcher;
055import java.util.regex.Pattern;
056import java.util.regex.PatternSyntaxException;
057import java.util.concurrent.TimeUnit;
058import java.util.concurrent.atomic.AtomicBoolean;
059import java.util.concurrent.atomic.AtomicReference;
060
061import javax.xml.parsers.DocumentBuilder;
062import javax.xml.parsers.DocumentBuilderFactory;
063import javax.xml.parsers.ParserConfigurationException;
064import javax.xml.transform.Transformer;
065import javax.xml.transform.TransformerException;
066import javax.xml.transform.TransformerFactory;
067import javax.xml.transform.dom.DOMSource;
068import javax.xml.transform.stream.StreamResult;
069
070import org.apache.commons.collections.map.UnmodifiableMap;
071import org.apache.commons.logging.Log;
072import org.apache.commons.logging.LogFactory;
073import org.apache.hadoop.classification.InterfaceAudience;
074import org.apache.hadoop.classification.InterfaceStability;
075import org.apache.hadoop.fs.FileSystem;
076import org.apache.hadoop.fs.Path;
077import org.apache.hadoop.fs.CommonConfigurationKeys;
078import org.apache.hadoop.io.Writable;
079import org.apache.hadoop.io.WritableUtils;
080import org.apache.hadoop.net.NetUtils;
081import org.apache.hadoop.security.alias.CredentialProvider;
082import org.apache.hadoop.security.alias.CredentialProvider.CredentialEntry;
083import org.apache.hadoop.security.alias.CredentialProviderFactory;
084import org.apache.hadoop.util.ReflectionUtils;
085import org.apache.hadoop.util.StringInterner;
086import org.apache.hadoop.util.StringUtils;
087import org.codehaus.jackson.JsonFactory;
088import org.codehaus.jackson.JsonGenerator;
089import org.w3c.dom.DOMException;
090import org.w3c.dom.Document;
091import org.w3c.dom.Element;
092import org.w3c.dom.Node;
093import org.w3c.dom.NodeList;
094import org.w3c.dom.Text;
095import org.xml.sax.SAXException;
096
097import com.google.common.base.Preconditions;
098
099/** 
100 * Provides access to configuration parameters.
101 *
102 * <h4 id="Resources">Resources</h4>
103 *
104 * <p>Configurations are specified by resources. A resource contains a set of
105 * name/value pairs as XML data. Each resource is named by either a 
106 * <code>String</code> or by a {@link Path}. If named by a <code>String</code>, 
107 * then the classpath is examined for a file with that name.  If named by a 
108 * <code>Path</code>, then the local filesystem is examined directly, without 
109 * referring to the classpath.
110 *
111 * <p>Unless explicitly turned off, Hadoop by default specifies two 
112 * resources, loaded in-order from the classpath: <ol>
113 * <li><tt>
114 * <a href="{@docRoot}/../hadoop-project-dist/hadoop-common/core-default.xml">
115 * core-default.xml</a></tt>: Read-only defaults for hadoop.</li>
116 * <li><tt>core-site.xml</tt>: Site-specific configuration for a given hadoop
117 * installation.</li>
118 * </ol>
119 * Applications may add additional resources, which are loaded
120 * subsequent to these resources in the order they are added.
121 * 
122 * <h4 id="FinalParams">Final Parameters</h4>
123 *
124 * <p>Configuration parameters may be declared <i>final</i>. 
125 * Once a resource declares a value final, no subsequently-loaded 
126 * resource can alter that value.  
127 * For example, one might define a final parameter with:
128 * <tt><pre>
129 *  &lt;property&gt;
130 *    &lt;name&gt;dfs.hosts.include&lt;/name&gt;
131 *    &lt;value&gt;/etc/hadoop/conf/hosts.include&lt;/value&gt;
132 *    <b>&lt;final&gt;true&lt;/final&gt;</b>
133 *  &lt;/property&gt;</pre></tt>
134 *
135 * Administrators typically define parameters as final in 
136 * <tt>core-site.xml</tt> for values that user applications may not alter.
137 *
138 * <h4 id="VariableExpansion">Variable Expansion</h4>
139 *
140 * <p>Value strings are first processed for <i>variable expansion</i>. The
141 * available properties are:<ol>
142 * <li>Other properties defined in this Configuration; and, if a name is
143 * undefined here,</li>
144 * <li>Properties in {@link System#getProperties()}.</li>
145 * </ol>
146 *
147 * <p>For example, if a configuration resource contains the following property
148 * definitions: 
149 * <tt><pre>
150 *  &lt;property&gt;
151 *    &lt;name&gt;basedir&lt;/name&gt;
152 *    &lt;value&gt;/user/${<i>user.name</i>}&lt;/value&gt;
153 *  &lt;/property&gt;
154 *  
155 *  &lt;property&gt;
156 *    &lt;name&gt;tempdir&lt;/name&gt;
157 *    &lt;value&gt;${<i>basedir</i>}/tmp&lt;/value&gt;
158 *  &lt;/property&gt;</pre></tt>
159 *
160 * When <tt>conf.get("tempdir")</tt> is called, then <tt>${<i>basedir</i>}</tt>
161 * will be resolved to another property in this Configuration, while
162 * <tt>${<i>user.name</i>}</tt> would then ordinarily be resolved to the value
163 * of the System property with that name.
164 * By default, warnings will be given to any deprecated configuration 
165 * parameters and these are suppressible by configuring
166 * <tt>log4j.logger.org.apache.hadoop.conf.Configuration.deprecation</tt> in
167 * log4j.properties file.
168 */
169@InterfaceAudience.Public
170@InterfaceStability.Stable
171public class Configuration implements Iterable<Map.Entry<String,String>>,
172                                      Writable {
173  private static final Log LOG =
174    LogFactory.getLog(Configuration.class);
175
176  private static final Log LOG_DEPRECATION =
177    LogFactory.getLog("org.apache.hadoop.conf.Configuration.deprecation");
178
179  private boolean quietmode = true;
180  
181  private static class Resource {
182    private final Object resource;
183    private final String name;
184    
185    public Resource(Object resource) {
186      this(resource, resource.toString());
187    }
188    
189    public Resource(Object resource, String name) {
190      this.resource = resource;
191      this.name = name;
192    }
193    
194    public String getName(){
195      return name;
196    }
197    
198    public Object getResource() {
199      return resource;
200    }
201    
202    @Override
203    public String toString() {
204      return name;
205    }
206  }
207  
208  /**
209   * List of configuration resources.
210   */
211  private ArrayList<Resource> resources = new ArrayList<Resource>();
212  
213  /**
214   * The value reported as the setting resource when a key is set
215   * by code rather than a file resource by dumpConfiguration.
216   */
217  static final String UNKNOWN_RESOURCE = "Unknown";
218
219
220  /**
221   * List of configuration parameters marked <b>final</b>. 
222   */
223  private Set<String> finalParameters = new HashSet<String>();
224  
225  private boolean loadDefaults = true;
226  
227  /**
228   * Configuration objects
229   */
230  private static final WeakHashMap<Configuration,Object> REGISTRY = 
231    new WeakHashMap<Configuration,Object>();
232  
233  /**
234   * List of default Resources. Resources are loaded in the order of the list 
235   * entries
236   */
237  private static final CopyOnWriteArrayList<String> defaultResources =
238    new CopyOnWriteArrayList<String>();
239
240  private static final Map<ClassLoader, Map<String, WeakReference<Class<?>>>>
241    CACHE_CLASSES = new WeakHashMap<ClassLoader, Map<String, WeakReference<Class<?>>>>();
242
243  /**
244   * Sentinel value to store negative cache results in {@link #CACHE_CLASSES}.
245   */
246  private static final Class<?> NEGATIVE_CACHE_SENTINEL =
247    NegativeCacheSentinel.class;
248
249  /**
250   * Stores the mapping of key to the resource which modifies or loads 
251   * the key most recently
252   */
253  private HashMap<String, String[]> updatingResource;
254 
255  /**
256   * Class to keep the information about the keys which replace the deprecated
257   * ones.
258   * 
259   * This class stores the new keys which replace the deprecated keys and also
260   * gives a provision to have a custom message for each of the deprecated key
261   * that is being replaced. It also provides method to get the appropriate
262   * warning message which can be logged whenever the deprecated key is used.
263   */
264  private static class DeprecatedKeyInfo {
265    private final String[] newKeys;
266    private final String customMessage;
267    private final AtomicBoolean accessed = new AtomicBoolean(false);
268
269    DeprecatedKeyInfo(String[] newKeys, String customMessage) {
270      this.newKeys = newKeys;
271      this.customMessage = customMessage;
272    }
273
274    /**
275     * Method to provide the warning message. It gives the custom message if
276     * non-null, and default message otherwise.
277     * @param key the associated deprecated key.
278     * @return message that is to be logged when a deprecated key is used.
279     */
280    private final String getWarningMessage(String key) {
281      String warningMessage;
282      if(customMessage == null) {
283        StringBuilder message = new StringBuilder(key);
284        String deprecatedKeySuffix = " is deprecated. Instead, use ";
285        message.append(deprecatedKeySuffix);
286        for (int i = 0; i < newKeys.length; i++) {
287          message.append(newKeys[i]);
288          if(i != newKeys.length-1) {
289            message.append(", ");
290          }
291        }
292        warningMessage = message.toString();
293      }
294      else {
295        warningMessage = customMessage;
296      }
297      return warningMessage;
298    }
299
300    boolean getAndSetAccessed() {
301      return accessed.getAndSet(true);
302    }
303
304    public void clearAccessed() {
305      accessed.set(false);
306    }
307  }
308  
309  /**
310   * A pending addition to the global set of deprecated keys.
311   */
312  public static class DeprecationDelta {
313    private final String key;
314    private final String[] newKeys;
315    private final String customMessage;
316
317    DeprecationDelta(String key, String[] newKeys, String customMessage) {
318      Preconditions.checkNotNull(key);
319      Preconditions.checkNotNull(newKeys);
320      Preconditions.checkArgument(newKeys.length > 0);
321      this.key = key;
322      this.newKeys = newKeys;
323      this.customMessage = customMessage;
324    }
325
326    public DeprecationDelta(String key, String newKey, String customMessage) {
327      this(key, new String[] { newKey }, customMessage);
328    }
329
330    public DeprecationDelta(String key, String newKey) {
331      this(key, new String[] { newKey }, null);
332    }
333
334    public String getKey() {
335      return key;
336    }
337
338    public String[] getNewKeys() {
339      return newKeys;
340    }
341
342    public String getCustomMessage() {
343      return customMessage;
344    }
345  }
346
347  /**
348   * The set of all keys which are deprecated.
349   *
350   * DeprecationContext objects are immutable.
351   */
352  private static class DeprecationContext {
353    /**
354     * Stores the deprecated keys, the new keys which replace the deprecated keys
355     * and custom message(if any provided).
356     */
357    private final Map<String, DeprecatedKeyInfo> deprecatedKeyMap;
358
359    /**
360     * Stores a mapping from superseding keys to the keys which they deprecate.
361     */
362    private final Map<String, String> reverseDeprecatedKeyMap;
363
364    /**
365     * Create a new DeprecationContext by copying a previous DeprecationContext
366     * and adding some deltas.
367     *
368     * @param other   The previous deprecation context to copy, or null to start
369     *                from nothing.
370     * @param deltas  The deltas to apply.
371     */
372    @SuppressWarnings("unchecked")
373    DeprecationContext(DeprecationContext other, DeprecationDelta[] deltas) {
374      HashMap<String, DeprecatedKeyInfo> newDeprecatedKeyMap = 
375        new HashMap<String, DeprecatedKeyInfo>();
376      HashMap<String, String> newReverseDeprecatedKeyMap =
377        new HashMap<String, String>();
378      if (other != null) {
379        for (Entry<String, DeprecatedKeyInfo> entry :
380            other.deprecatedKeyMap.entrySet()) {
381          newDeprecatedKeyMap.put(entry.getKey(), entry.getValue());
382        }
383        for (Entry<String, String> entry :
384            other.reverseDeprecatedKeyMap.entrySet()) {
385          newReverseDeprecatedKeyMap.put(entry.getKey(), entry.getValue());
386        }
387      }
388      for (DeprecationDelta delta : deltas) {
389        if (!newDeprecatedKeyMap.containsKey(delta.getKey())) {
390          DeprecatedKeyInfo newKeyInfo =
391            new DeprecatedKeyInfo(delta.getNewKeys(), delta.getCustomMessage());
392          newDeprecatedKeyMap.put(delta.key, newKeyInfo);
393          for (String newKey : delta.getNewKeys()) {
394            newReverseDeprecatedKeyMap.put(newKey, delta.key);
395          }
396        }
397      }
398      this.deprecatedKeyMap =
399        UnmodifiableMap.decorate(newDeprecatedKeyMap);
400      this.reverseDeprecatedKeyMap =
401        UnmodifiableMap.decorate(newReverseDeprecatedKeyMap);
402    }
403
404    Map<String, DeprecatedKeyInfo> getDeprecatedKeyMap() {
405      return deprecatedKeyMap;
406    }
407
408    Map<String, String> getReverseDeprecatedKeyMap() {
409      return reverseDeprecatedKeyMap;
410    }
411  }
412  
413  private static DeprecationDelta[] defaultDeprecations = 
414    new DeprecationDelta[] {
415      new DeprecationDelta("topology.script.file.name", 
416        CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY),
417      new DeprecationDelta("topology.script.number.args", 
418        CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_NUMBER_ARGS_KEY),
419      new DeprecationDelta("hadoop.configured.node.mapping", 
420        CommonConfigurationKeys.NET_TOPOLOGY_CONFIGURED_NODE_MAPPING_KEY),
421      new DeprecationDelta("topology.node.switch.mapping.impl", 
422        CommonConfigurationKeys.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY),
423      new DeprecationDelta("dfs.df.interval", 
424        CommonConfigurationKeys.FS_DF_INTERVAL_KEY),
425      new DeprecationDelta("hadoop.native.lib", 
426        CommonConfigurationKeys.IO_NATIVE_LIB_AVAILABLE_KEY),
427      new DeprecationDelta("fs.default.name", 
428        CommonConfigurationKeys.FS_DEFAULT_NAME_KEY),
429      new DeprecationDelta("dfs.umaskmode",
430        CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY),
431      new DeprecationDelta("dfs.nfs.exports.allowed.hosts",
432          CommonConfigurationKeys.NFS_EXPORTS_ALLOWED_HOSTS_KEY)
433    };
434
435  /**
436   * The global DeprecationContext.
437   */
438  private static AtomicReference<DeprecationContext> deprecationContext =
439      new AtomicReference<DeprecationContext>(
440          new DeprecationContext(null, defaultDeprecations));
441
442  /**
443   * Adds a set of deprecated keys to the global deprecations.
444   *
445   * This method is lockless.  It works by means of creating a new
446   * DeprecationContext based on the old one, and then atomically swapping in
447   * the new context.  If someone else updated the context in between us reading
448   * the old context and swapping in the new one, we try again until we win the
449   * race.
450   *
451   * @param deltas   The deprecations to add.
452   */
453  public static void addDeprecations(DeprecationDelta[] deltas) {
454    DeprecationContext prev, next;
455    do {
456      prev = deprecationContext.get();
457      next = new DeprecationContext(prev, deltas);
458    } while (!deprecationContext.compareAndSet(prev, next));
459  }
460
461  /**
462   * Adds the deprecated key to the global deprecation map.
463   * It does not override any existing entries in the deprecation map.
464   * This is to be used only by the developers in order to add deprecation of
465   * keys, and attempts to call this method after loading resources once,
466   * would lead to <tt>UnsupportedOperationException</tt>
467   * 
468   * If a key is deprecated in favor of multiple keys, they are all treated as 
469   * aliases of each other, and setting any one of them resets all the others 
470   * to the new value.
471   *
472   * If you have multiple deprecation entries to add, it is more efficient to
473   * use #addDeprecations(DeprecationDelta[] deltas) instead.
474   * 
475   * @param key
476   * @param newKeys
477   * @param customMessage
478   * @deprecated use {@link #addDeprecation(String key, String newKey,
479      String customMessage)} instead
480   */
481  @Deprecated
482  public static void addDeprecation(String key, String[] newKeys,
483      String customMessage) {
484    addDeprecations(new DeprecationDelta[] {
485      new DeprecationDelta(key, newKeys, customMessage)
486    });
487  }
488
489  /**
490   * Adds the deprecated key to the global deprecation map.
491   * It does not override any existing entries in the deprecation map.
492   * This is to be used only by the developers in order to add deprecation of
493   * keys, and attempts to call this method after loading resources once,
494   * would lead to <tt>UnsupportedOperationException</tt>
495   * 
496   * If you have multiple deprecation entries to add, it is more efficient to
497   * use #addDeprecations(DeprecationDelta[] deltas) instead.
498   *
499   * @param key
500   * @param newKey
501   * @param customMessage
502   */
503  public static void addDeprecation(String key, String newKey,
504              String customMessage) {
505          addDeprecation(key, new String[] {newKey}, customMessage);
506  }
507
508  /**
509   * Adds the deprecated key to the global deprecation map when no custom
510   * message is provided.
511   * It does not override any existing entries in the deprecation map.
512   * This is to be used only by the developers in order to add deprecation of
513   * keys, and attempts to call this method after loading resources once,
514   * would lead to <tt>UnsupportedOperationException</tt>
515   * 
516   * If a key is deprecated in favor of multiple keys, they are all treated as 
517   * aliases of each other, and setting any one of them resets all the others 
518   * to the new value.
519   * 
520   * If you have multiple deprecation entries to add, it is more efficient to
521   * use #addDeprecations(DeprecationDelta[] deltas) instead.
522   *
523   * @param key Key that is to be deprecated
524   * @param newKeys list of keys that take up the values of deprecated key
525   * @deprecated use {@link #addDeprecation(String key, String newKey)} instead
526   */
527  @Deprecated
528  public static void addDeprecation(String key, String[] newKeys) {
529    addDeprecation(key, newKeys, null);
530  }
531  
532  /**
533   * Adds the deprecated key to the global deprecation map when no custom
534   * message is provided.
535   * It does not override any existing entries in the deprecation map.
536   * This is to be used only by the developers in order to add deprecation of
537   * keys, and attempts to call this method after loading resources once,
538   * would lead to <tt>UnsupportedOperationException</tt>
539   * 
540   * If you have multiple deprecation entries to add, it is more efficient to
541   * use #addDeprecations(DeprecationDelta[] deltas) instead.
542   *
543   * @param key Key that is to be deprecated
544   * @param newKey key that takes up the value of deprecated key
545   */
546  public static void addDeprecation(String key, String newKey) {
547    addDeprecation(key, new String[] {newKey}, null);
548  }
549  
550  /**
551   * checks whether the given <code>key</code> is deprecated.
552   * 
553   * @param key the parameter which is to be checked for deprecation
554   * @return <code>true</code> if the key is deprecated and 
555   *         <code>false</code> otherwise.
556   */
557  public static boolean isDeprecated(String key) {
558    return deprecationContext.get().getDeprecatedKeyMap().containsKey(key);
559  }
560
561  /**
562   * Sets all deprecated properties that are not currently set but have a
563   * corresponding new property that is set. Useful for iterating the
564   * properties when all deprecated properties for currently set properties
565   * need to be present.
566   */
567  public void setDeprecatedProperties() {
568    DeprecationContext deprecations = deprecationContext.get();
569    Properties props = getProps();
570    Properties overlay = getOverlay();
571    for (Map.Entry<String, DeprecatedKeyInfo> entry :
572        deprecations.getDeprecatedKeyMap().entrySet()) {
573      String depKey = entry.getKey();
574      if (!overlay.contains(depKey)) {
575        for (String newKey : entry.getValue().newKeys) {
576          String val = overlay.getProperty(newKey);
577          if (val != null) {
578            props.setProperty(depKey, val);
579            overlay.setProperty(depKey, val);
580            break;
581          }
582        }
583      }
584    }
585  }
586
587  /**
588   * Checks for the presence of the property <code>name</code> in the
589   * deprecation map. Returns the first of the list of new keys if present
590   * in the deprecation map or the <code>name</code> itself. If the property
591   * is not presently set but the property map contains an entry for the
592   * deprecated key, the value of the deprecated key is set as the value for
593   * the provided property name.
594   *
595   * @param name the property name
596   * @return the first property in the list of properties mapping
597   *         the <code>name</code> or the <code>name</code> itself.
598   */
599  private String[] handleDeprecation(DeprecationContext deprecations,
600      String name) {
601    if (null != name) {
602      name = name.trim();
603    }
604    ArrayList<String > names = new ArrayList<String>();
605        if (isDeprecated(name)) {
606      DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(name);
607      warnOnceIfDeprecated(deprecations, name);
608      for (String newKey : keyInfo.newKeys) {
609        if(newKey != null) {
610          names.add(newKey);
611        }
612      }
613    }
614    if(names.size() == 0) {
615        names.add(name);
616    }
617    for(String n : names) {
618          String deprecatedKey = deprecations.getReverseDeprecatedKeyMap().get(n);
619          if (deprecatedKey != null && !getOverlay().containsKey(n) &&
620              getOverlay().containsKey(deprecatedKey)) {
621            getProps().setProperty(n, getOverlay().getProperty(deprecatedKey));
622            getOverlay().setProperty(n, getOverlay().getProperty(deprecatedKey));
623          }
624    }
625    return names.toArray(new String[names.size()]);
626  }
627 
628  private void handleDeprecation() {
629    LOG.debug("Handling deprecation for all properties in config...");
630    DeprecationContext deprecations = deprecationContext.get();
631    Set<Object> keys = new HashSet<Object>();
632    keys.addAll(getProps().keySet());
633    for (Object item: keys) {
634      LOG.debug("Handling deprecation for " + (String)item);
635      handleDeprecation(deprecations, (String)item);
636    }
637  }
638 
639  static{
640    //print deprecation warning if hadoop-site.xml is found in classpath
641    ClassLoader cL = Thread.currentThread().getContextClassLoader();
642    if (cL == null) {
643      cL = Configuration.class.getClassLoader();
644    }
645    if(cL.getResource("hadoop-site.xml")!=null) {
646      LOG.warn("DEPRECATED: hadoop-site.xml found in the classpath. " +
647          "Usage of hadoop-site.xml is deprecated. Instead use core-site.xml, "
648          + "mapred-site.xml and hdfs-site.xml to override properties of " +
649          "core-default.xml, mapred-default.xml and hdfs-default.xml " +
650          "respectively");
651    }
652    addDefaultResource("core-default.xml");
653    addDefaultResource("core-site.xml");
654  }
655  
656  private Properties properties;
657  private Properties overlay;
658  private ClassLoader classLoader;
659  {
660    classLoader = Thread.currentThread().getContextClassLoader();
661    if (classLoader == null) {
662      classLoader = Configuration.class.getClassLoader();
663    }
664  }
665  
666  /** A new configuration. */
667  public Configuration() {
668    this(true);
669  }
670
671  /** A new configuration where the behavior of reading from the default 
672   * resources can be turned off.
673   * 
674   * If the parameter {@code loadDefaults} is false, the new instance
675   * will not load resources from the default files. 
676   * @param loadDefaults specifies whether to load from the default files
677   */
678  public Configuration(boolean loadDefaults) {
679    this.loadDefaults = loadDefaults;
680    updatingResource = new HashMap<String, String[]>();
681    synchronized(Configuration.class) {
682      REGISTRY.put(this, null);
683    }
684  }
685  
686  /** 
687   * A new configuration with the same settings cloned from another.
688   * 
689   * @param other the configuration from which to clone settings.
690   */
691  @SuppressWarnings("unchecked")
692  public Configuration(Configuration other) {
693   this.resources = (ArrayList<Resource>) other.resources.clone();
694   synchronized(other) {
695     if (other.properties != null) {
696       this.properties = (Properties)other.properties.clone();
697     }
698
699     if (other.overlay!=null) {
700       this.overlay = (Properties)other.overlay.clone();
701     }
702
703     this.updatingResource = new HashMap<String, String[]>(other.updatingResource);
704     this.finalParameters = new HashSet<String>(other.finalParameters);
705   }
706   
707    synchronized(Configuration.class) {
708      REGISTRY.put(this, null);
709    }
710    this.classLoader = other.classLoader;
711    this.loadDefaults = other.loadDefaults;
712    setQuietMode(other.getQuietMode());
713  }
714  
715  /**
716   * Add a default resource. Resources are loaded in the order of the resources 
717   * added.
718   * @param name file name. File should be present in the classpath.
719   */
720  public static synchronized void addDefaultResource(String name) {
721    if(!defaultResources.contains(name)) {
722      defaultResources.add(name);
723      for(Configuration conf : REGISTRY.keySet()) {
724        if(conf.loadDefaults) {
725          conf.reloadConfiguration();
726        }
727      }
728    }
729  }
730
731  /**
732   * Add a configuration resource. 
733   * 
734   * The properties of this resource will override properties of previously 
735   * added resources, unless they were marked <a href="#Final">final</a>. 
736   * 
737   * @param name resource to be added, the classpath is examined for a file 
738   *             with that name.
739   */
740  public void addResource(String name) {
741    addResourceObject(new Resource(name));
742  }
743
744  /**
745   * Add a configuration resource. 
746   * 
747   * The properties of this resource will override properties of previously 
748   * added resources, unless they were marked <a href="#Final">final</a>. 
749   * 
750   * @param url url of the resource to be added, the local filesystem is 
751   *            examined directly to find the resource, without referring to 
752   *            the classpath.
753   */
754  public void addResource(URL url) {
755    addResourceObject(new Resource(url));
756  }
757
758  /**
759   * Add a configuration resource. 
760   * 
761   * The properties of this resource will override properties of previously 
762   * added resources, unless they were marked <a href="#Final">final</a>. 
763   * 
764   * @param file file-path of resource to be added, the local filesystem is
765   *             examined directly to find the resource, without referring to 
766   *             the classpath.
767   */
768  public void addResource(Path file) {
769    addResourceObject(new Resource(file));
770  }
771
772  /**
773   * Add a configuration resource. 
774   * 
775   * The properties of this resource will override properties of previously 
776   * added resources, unless they were marked <a href="#Final">final</a>. 
777   * 
778   * WARNING: The contents of the InputStream will be cached, by this method. 
779   * So use this sparingly because it does increase the memory consumption.
780   * 
781   * @param in InputStream to deserialize the object from. In will be read from
782   * when a get or set is called next.  After it is read the stream will be
783   * closed. 
784   */
785  public void addResource(InputStream in) {
786    addResourceObject(new Resource(in));
787  }
788
789  /**
790   * Add a configuration resource. 
791   * 
792   * The properties of this resource will override properties of previously 
793   * added resources, unless they were marked <a href="#Final">final</a>. 
794   * 
795   * @param in InputStream to deserialize the object from.
796   * @param name the name of the resource because InputStream.toString is not
797   * very descriptive some times.  
798   */
799  public void addResource(InputStream in, String name) {
800    addResourceObject(new Resource(in, name));
801  }
802  
803  /**
804   * Add a configuration resource.
805   *
806   * The properties of this resource will override properties of previously
807   * added resources, unless they were marked <a href="#Final">final</a>.
808   *
809   * @param conf Configuration object from which to load properties
810   */
811  public void addResource(Configuration conf) {
812    addResourceObject(new Resource(conf.getProps()));
813  }
814
815  
816  
817  /**
818   * Reload configuration from previously added resources.
819   *
820   * This method will clear all the configuration read from the added 
821   * resources, and final parameters. This will make the resources to 
822   * be read again before accessing the values. Values that are added
823   * via set methods will overlay values read from the resources.
824   */
825  public synchronized void reloadConfiguration() {
826    properties = null;                            // trigger reload
827    finalParameters.clear();                      // clear site-limits
828  }
829  
830  private synchronized void addResourceObject(Resource resource) {
831    resources.add(resource);                      // add to resources
832    reloadConfiguration();
833  }
834
835  private static final int MAX_SUBST = 20;
836
837  private static final int SUB_START_IDX = 0;
838  private static final int SUB_END_IDX = SUB_START_IDX + 1;
839
840  /**
841   * This is a manual implementation of the following regex
842   * "\\$\\{[^\\}\\$\u0020]+\\}". It can be 15x more efficient than
843   * a regex matcher as demonstrated by HADOOP-11506. This is noticeable with
844   * Hadoop apps building on the assumption Configuration#get is an O(1)
845   * hash table lookup, especially when the eval is a long string.
846   *
847   * @param eval a string that may contain variables requiring expansion.
848   * @return a 2-element int array res such that
849   * eval.substring(res[0], res[1]) is "var" for the left-most occurrence of
850   * ${var} in eval. If no variable is found -1, -1 is returned.
851   */
852  private static int[] findSubVariable(String eval) {
853    int[] result = {-1, -1};
854
855    int matchStart;
856    int leftBrace;
857
858    // scanning for a brace first because it's less frequent than $
859    // that can occur in nested class names
860    //
861    match_loop:
862    for (matchStart = 1, leftBrace = eval.indexOf('{', matchStart);
863         // minimum left brace position (follows '$')
864         leftBrace > 0
865         // right brace of a smallest valid expression "${c}"
866         && leftBrace + "{c".length() < eval.length();
867         leftBrace = eval.indexOf('{', matchStart)) {
868      int matchedLen = 0;
869      if (eval.charAt(leftBrace - 1) == '$') {
870        int subStart = leftBrace + 1; // after '{'
871        for (int i = subStart; i < eval.length(); i++) {
872          switch (eval.charAt(i)) {
873            case '}':
874              if (matchedLen > 0) { // match
875                result[SUB_START_IDX] = subStart;
876                result[SUB_END_IDX] = subStart + matchedLen;
877                break match_loop;
878              }
879              // fall through to skip 1 char
880            case ' ':
881            case '$':
882              matchStart = i + 1;
883              continue match_loop;
884            default:
885              matchedLen++;
886          }
887        }
888        // scanned from "${"  to the end of eval, and no reset via ' ', '$':
889        //    no match!
890        break match_loop;
891      } else {
892        // not a start of a variable
893        //
894        matchStart = leftBrace + 1;
895      }
896    }
897    return result;
898  }
899
900  /**
901   * Attempts to repeatedly expand the value {@code expr} by replacing the
902   * left-most substring of the form "${var}" in the following precedence order
903   * <ol>
904   *   <li>by the value of the Java system property "var" if defined</li>
905   *   <li>by the value of the configuration key "var" if defined</li>
906   * </ol>
907   *
908   * If var is unbounded the current state of expansion "prefix${var}suffix" is
909   * returned.
910   *
911   * @param expr the literal value of a config key
912   * @return null if expr is null, otherwise the value resulting from expanding
913   * expr using the algorithm above.
914   * @throws IllegalArgumentException when more than
915   * {@link Configuration#MAX_SUBST} replacements are required
916   */
917  private String substituteVars(String expr) {
918    if (expr == null) {
919      return null;
920    }
921    String eval = expr;
922    for (int s = 0; s < MAX_SUBST; s++) {
923      final int[] varBounds = findSubVariable(eval);
924      if (varBounds[SUB_START_IDX] == -1) {
925        return eval;
926      }
927      final String var = eval.substring(varBounds[SUB_START_IDX],
928          varBounds[SUB_END_IDX]);
929      String val = null;
930      try {
931        val = System.getProperty(var);
932      } catch(SecurityException se) {
933        LOG.warn("Unexpected SecurityException in Configuration", se);
934      }
935      if (val == null) {
936        val = getRaw(var);
937      }
938      if (val == null) {
939        return eval; // return literal ${var}: var is unbound
940      }
941      final int dollar = varBounds[SUB_START_IDX] - "${".length();
942      final int afterRightBrace = varBounds[SUB_END_IDX] + "}".length();
943      // substitute
944      eval = eval.substring(0, dollar)
945             + val
946             + eval.substring(afterRightBrace);
947    }
948    throw new IllegalStateException("Variable substitution depth too large: " 
949                                    + MAX_SUBST + " " + expr);
950  }
951  
952  /**
953   * Get the value of the <code>name</code> property, <code>null</code> if
954   * no such property exists. If the key is deprecated, it returns the value of
955   * the first key which replaces the deprecated key and is not null.
956   * 
957   * Values are processed for <a href="#VariableExpansion">variable expansion</a> 
958   * before being returned. 
959   * 
960   * @param name the property name, will be trimmed before get value.
961   * @return the value of the <code>name</code> or its replacing property, 
962   *         or null if no such property exists.
963   */
964  public String get(String name) {
965    String[] names = handleDeprecation(deprecationContext.get(), name);
966    String result = null;
967    for(String n : names) {
968      result = substituteVars(getProps().getProperty(n));
969    }
970    return result;
971  }
972  
973  /**
974   * Get the value of the <code>name</code> property as a trimmed <code>String</code>, 
975   * <code>null</code> if no such property exists. 
976   * If the key is deprecated, it returns the value of
977   * the first key which replaces the deprecated key and is not null
978   * 
979   * Values are processed for <a href="#VariableExpansion">variable expansion</a> 
980   * before being returned. 
981   * 
982   * @param name the property name.
983   * @return the value of the <code>name</code> or its replacing property, 
984   *         or null if no such property exists.
985   */
986  public String getTrimmed(String name) {
987    String value = get(name);
988    
989    if (null == value) {
990      return null;
991    } else {
992      return value.trim();
993    }
994  }
995  
996  /**
997   * Get the value of the <code>name</code> property as a trimmed <code>String</code>, 
998   * <code>defaultValue</code> if no such property exists. 
999   * See @{Configuration#getTrimmed} for more details.
1000   * 
1001   * @param name          the property name.
1002   * @param defaultValue  the property default value.
1003   * @return              the value of the <code>name</code> or defaultValue
1004   *                      if it is not set.
1005   */
1006  public String getTrimmed(String name, String defaultValue) {
1007    String ret = getTrimmed(name);
1008    return ret == null ? defaultValue : ret;
1009  }
1010
1011  /**
1012   * Get the value of the <code>name</code> property, without doing
1013   * <a href="#VariableExpansion">variable expansion</a>.If the key is 
1014   * deprecated, it returns the value of the first key which replaces 
1015   * the deprecated key and is not null.
1016   * 
1017   * @param name the property name.
1018   * @return the value of the <code>name</code> property or 
1019   *         its replacing property and null if no such property exists.
1020   */
1021  public String getRaw(String name) {
1022    String[] names = handleDeprecation(deprecationContext.get(), name);
1023    String result = null;
1024    for(String n : names) {
1025      result = getProps().getProperty(n);
1026    }
1027    return result;
1028  }
1029
1030  /**
1031   * Returns alternative names (non-deprecated keys or previously-set deprecated keys)
1032   * for a given non-deprecated key.
1033   * If the given key is deprecated, return null.
1034   *
1035   * @param name property name.
1036   * @return alternative names.
1037   */
1038  private String[] getAlternativeNames(String name) {
1039    String altNames[] = null;
1040    DeprecatedKeyInfo keyInfo = null;
1041    DeprecationContext cur = deprecationContext.get();
1042    String depKey = cur.getReverseDeprecatedKeyMap().get(name);
1043    if(depKey != null) {
1044      keyInfo = cur.getDeprecatedKeyMap().get(depKey);
1045      if(keyInfo.newKeys.length > 0) {
1046        if(getProps().containsKey(depKey)) {
1047          //if deprecated key is previously set explicitly
1048          List<String> list = new ArrayList<String>();
1049          list.addAll(Arrays.asList(keyInfo.newKeys));
1050          list.add(depKey);
1051          altNames = list.toArray(new String[list.size()]);
1052        }
1053        else {
1054          altNames = keyInfo.newKeys;
1055        }
1056      }
1057    }
1058    return altNames;
1059  }
1060
1061  /** 
1062   * Set the <code>value</code> of the <code>name</code> property. If 
1063   * <code>name</code> is deprecated or there is a deprecated name associated to it,
1064   * it sets the value to both names. Name will be trimmed before put into
1065   * configuration.
1066   * 
1067   * @param name property name.
1068   * @param value property value.
1069   */
1070  public void set(String name, String value) {
1071    set(name, value, null);
1072  }
1073  
1074  /** 
1075   * Set the <code>value</code> of the <code>name</code> property. If 
1076   * <code>name</code> is deprecated, it also sets the <code>value</code> to
1077   * the keys that replace the deprecated key. Name will be trimmed before put
1078   * into configuration.
1079   *
1080   * @param name property name.
1081   * @param value property value.
1082   * @param source the place that this configuration value came from 
1083   * (For debugging).
1084   * @throws IllegalArgumentException when the value or name is null.
1085   */
1086  public void set(String name, String value, String source) {
1087    Preconditions.checkArgument(
1088        name != null,
1089        "Property name must not be null");
1090    Preconditions.checkArgument(
1091        value != null,
1092        "The value of property " + name + " must not be null");
1093    name = name.trim();
1094    DeprecationContext deprecations = deprecationContext.get();
1095    if (deprecations.getDeprecatedKeyMap().isEmpty()) {
1096      getProps();
1097    }
1098    getOverlay().setProperty(name, value);
1099    getProps().setProperty(name, value);
1100    String newSource = (source == null ? "programatically" : source);
1101
1102    if (!isDeprecated(name)) {
1103      updatingResource.put(name, new String[] {newSource});
1104      String[] altNames = getAlternativeNames(name);
1105      if(altNames != null) {
1106        for(String n: altNames) {
1107          if(!n.equals(name)) {
1108            getOverlay().setProperty(n, value);
1109            getProps().setProperty(n, value);
1110            updatingResource.put(n, new String[] {newSource});
1111          }
1112        }
1113      }
1114    }
1115    else {
1116      String[] names = handleDeprecation(deprecationContext.get(), name);
1117      String altSource = "because " + name + " is deprecated";
1118      for(String n : names) {
1119        getOverlay().setProperty(n, value);
1120        getProps().setProperty(n, value);
1121        updatingResource.put(n, new String[] {altSource});
1122      }
1123    }
1124  }
1125
1126  private void warnOnceIfDeprecated(DeprecationContext deprecations, String name) {
1127    DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(name);
1128    if (keyInfo != null && !keyInfo.getAndSetAccessed()) {
1129      LOG_DEPRECATION.info(keyInfo.getWarningMessage(name));
1130    }
1131  }
1132
1133  /**
1134   * Unset a previously set property.
1135   */
1136  public synchronized void unset(String name) {
1137    String[] names = null;
1138    if (!isDeprecated(name)) {
1139      names = getAlternativeNames(name);
1140      if(names == null) {
1141          names = new String[]{name};
1142      }
1143    }
1144    else {
1145      names = handleDeprecation(deprecationContext.get(), name);
1146    }
1147
1148    for(String n: names) {
1149      getOverlay().remove(n);
1150      getProps().remove(n);
1151    }
1152  }
1153
1154  /**
1155   * Sets a property if it is currently unset.
1156   * @param name the property name
1157   * @param value the new value
1158   */
1159  public synchronized void setIfUnset(String name, String value) {
1160    if (get(name) == null) {
1161      set(name, value);
1162    }
1163  }
1164  
1165  private synchronized Properties getOverlay() {
1166    if (overlay==null){
1167      overlay=new Properties();
1168    }
1169    return overlay;
1170  }
1171
1172  /** 
1173   * Get the value of the <code>name</code>. If the key is deprecated,
1174   * it returns the value of the first key which replaces the deprecated key
1175   * and is not null.
1176   * If no such property exists,
1177   * then <code>defaultValue</code> is returned.
1178   * 
1179   * @param name property name, will be trimmed before get value.
1180   * @param defaultValue default value.
1181   * @return property value, or <code>defaultValue</code> if the property 
1182   *         doesn't exist.                    
1183   */
1184  public String get(String name, String defaultValue) {
1185    String[] names = handleDeprecation(deprecationContext.get(), name);
1186    String result = null;
1187    for(String n : names) {
1188      result = substituteVars(getProps().getProperty(n, defaultValue));
1189    }
1190    return result;
1191  }
1192
1193  /** 
1194   * Get the value of the <code>name</code> property as an <code>int</code>.
1195   *   
1196   * If no such property exists, the provided default value is returned,
1197   * or if the specified value is not a valid <code>int</code>,
1198   * then an error is thrown.
1199   * 
1200   * @param name property name.
1201   * @param defaultValue default value.
1202   * @throws NumberFormatException when the value is invalid
1203   * @return property value as an <code>int</code>, 
1204   *         or <code>defaultValue</code>. 
1205   */
1206  public int getInt(String name, int defaultValue) {
1207    String valueString = getTrimmed(name);
1208    if (valueString == null)
1209      return defaultValue;
1210    String hexString = getHexDigits(valueString);
1211    if (hexString != null) {
1212      return Integer.parseInt(hexString, 16);
1213    }
1214    return Integer.parseInt(valueString);
1215  }
1216  
1217  /**
1218   * Get the value of the <code>name</code> property as a set of comma-delimited
1219   * <code>int</code> values.
1220   * 
1221   * If no such property exists, an empty array is returned.
1222   * 
1223   * @param name property name
1224   * @return property value interpreted as an array of comma-delimited
1225   *         <code>int</code> values
1226   */
1227  public int[] getInts(String name) {
1228    String[] strings = getTrimmedStrings(name);
1229    int[] ints = new int[strings.length];
1230    for (int i = 0; i < strings.length; i++) {
1231      ints[i] = Integer.parseInt(strings[i]);
1232    }
1233    return ints;
1234  }
1235
1236  /** 
1237   * Set the value of the <code>name</code> property to an <code>int</code>.
1238   * 
1239   * @param name property name.
1240   * @param value <code>int</code> value of the property.
1241   */
1242  public void setInt(String name, int value) {
1243    set(name, Integer.toString(value));
1244  }
1245
1246
1247  /** 
1248   * Get the value of the <code>name</code> property as a <code>long</code>.  
1249   * If no such property exists, the provided default value is returned,
1250   * or if the specified value is not a valid <code>long</code>,
1251   * then an error is thrown.
1252   * 
1253   * @param name property name.
1254   * @param defaultValue default value.
1255   * @throws NumberFormatException when the value is invalid
1256   * @return property value as a <code>long</code>, 
1257   *         or <code>defaultValue</code>. 
1258   */
1259  public long getLong(String name, long defaultValue) {
1260    String valueString = getTrimmed(name);
1261    if (valueString == null)
1262      return defaultValue;
1263    String hexString = getHexDigits(valueString);
1264    if (hexString != null) {
1265      return Long.parseLong(hexString, 16);
1266    }
1267    return Long.parseLong(valueString);
1268  }
1269
1270  /**
1271   * Get the value of the <code>name</code> property as a <code>long</code> or
1272   * human readable format. If no such property exists, the provided default
1273   * value is returned, or if the specified value is not a valid
1274   * <code>long</code> or human readable format, then an error is thrown. You
1275   * can use the following suffix (case insensitive): k(kilo), m(mega), g(giga),
1276   * t(tera), p(peta), e(exa)
1277   *
1278   * @param name property name.
1279   * @param defaultValue default value.
1280   * @throws NumberFormatException when the value is invalid
1281   * @return property value as a <code>long</code>,
1282   *         or <code>defaultValue</code>.
1283   */
1284  public long getLongBytes(String name, long defaultValue) {
1285    String valueString = getTrimmed(name);
1286    if (valueString == null)
1287      return defaultValue;
1288    return StringUtils.TraditionalBinaryPrefix.string2long(valueString);
1289  }
1290
1291  private String getHexDigits(String value) {
1292    boolean negative = false;
1293    String str = value;
1294    String hexString = null;
1295    if (value.startsWith("-")) {
1296      negative = true;
1297      str = value.substring(1);
1298    }
1299    if (str.startsWith("0x") || str.startsWith("0X")) {
1300      hexString = str.substring(2);
1301      if (negative) {
1302        hexString = "-" + hexString;
1303      }
1304      return hexString;
1305    }
1306    return null;
1307  }
1308  
1309  /** 
1310   * Set the value of the <code>name</code> property to a <code>long</code>.
1311   * 
1312   * @param name property name.
1313   * @param value <code>long</code> value of the property.
1314   */
1315  public void setLong(String name, long value) {
1316    set(name, Long.toString(value));
1317  }
1318
1319  /** 
1320   * Get the value of the <code>name</code> property as a <code>float</code>.  
1321   * If no such property exists, the provided default value is returned,
1322   * or if the specified value is not a valid <code>float</code>,
1323   * then an error is thrown.
1324   *
1325   * @param name property name.
1326   * @param defaultValue default value.
1327   * @throws NumberFormatException when the value is invalid
1328   * @return property value as a <code>float</code>, 
1329   *         or <code>defaultValue</code>. 
1330   */
1331  public float getFloat(String name, float defaultValue) {
1332    String valueString = getTrimmed(name);
1333    if (valueString == null)
1334      return defaultValue;
1335    return Float.parseFloat(valueString);
1336  }
1337
1338  /**
1339   * Set the value of the <code>name</code> property to a <code>float</code>.
1340   * 
1341   * @param name property name.
1342   * @param value property value.
1343   */
1344  public void setFloat(String name, float value) {
1345    set(name,Float.toString(value));
1346  }
1347
1348  /** 
1349   * Get the value of the <code>name</code> property as a <code>double</code>.  
1350   * If no such property exists, the provided default value is returned,
1351   * or if the specified value is not a valid <code>double</code>,
1352   * then an error is thrown.
1353   *
1354   * @param name property name.
1355   * @param defaultValue default value.
1356   * @throws NumberFormatException when the value is invalid
1357   * @return property value as a <code>double</code>, 
1358   *         or <code>defaultValue</code>. 
1359   */
1360  public double getDouble(String name, double defaultValue) {
1361    String valueString = getTrimmed(name);
1362    if (valueString == null)
1363      return defaultValue;
1364    return Double.parseDouble(valueString);
1365  }
1366
1367  /**
1368   * Set the value of the <code>name</code> property to a <code>double</code>.
1369   * 
1370   * @param name property name.
1371   * @param value property value.
1372   */
1373  public void setDouble(String name, double value) {
1374    set(name,Double.toString(value));
1375  }
1376 
1377  /** 
1378   * Get the value of the <code>name</code> property as a <code>boolean</code>.  
1379   * If no such property is specified, or if the specified value is not a valid
1380   * <code>boolean</code>, then <code>defaultValue</code> is returned.
1381   * 
1382   * @param name property name.
1383   * @param defaultValue default value.
1384   * @return property value as a <code>boolean</code>, 
1385   *         or <code>defaultValue</code>. 
1386   */
1387  public boolean getBoolean(String name, boolean defaultValue) {
1388    String valueString = getTrimmed(name);
1389    if (null == valueString || valueString.isEmpty()) {
1390      return defaultValue;
1391    }
1392
1393    valueString = valueString.toLowerCase();
1394
1395    if ("true".equals(valueString))
1396      return true;
1397    else if ("false".equals(valueString))
1398      return false;
1399    else return defaultValue;
1400  }
1401
1402  /** 
1403   * Set the value of the <code>name</code> property to a <code>boolean</code>.
1404   * 
1405   * @param name property name.
1406   * @param value <code>boolean</code> value of the property.
1407   */
1408  public void setBoolean(String name, boolean value) {
1409    set(name, Boolean.toString(value));
1410  }
1411
1412  /**
1413   * Set the given property, if it is currently unset.
1414   * @param name property name
1415   * @param value new value
1416   */
1417  public void setBooleanIfUnset(String name, boolean value) {
1418    setIfUnset(name, Boolean.toString(value));
1419  }
1420
1421  /**
1422   * Set the value of the <code>name</code> property to the given type. This
1423   * is equivalent to <code>set(&lt;name&gt;, value.toString())</code>.
1424   * @param name property name
1425   * @param value new value
1426   */
1427  public <T extends Enum<T>> void setEnum(String name, T value) {
1428    set(name, value.toString());
1429  }
1430
1431  /**
1432   * Return value matching this enumerated type.
1433   * @param name Property name
1434   * @param defaultValue Value returned if no mapping exists
1435   * @throws IllegalArgumentException If mapping is illegal for the type
1436   * provided
1437   */
1438  public <T extends Enum<T>> T getEnum(String name, T defaultValue) {
1439    final String val = get(name);
1440    return null == val
1441      ? defaultValue
1442      : Enum.valueOf(defaultValue.getDeclaringClass(), val);
1443  }
1444
1445  enum ParsedTimeDuration {
1446    NS {
1447      TimeUnit unit() { return TimeUnit.NANOSECONDS; }
1448      String suffix() { return "ns"; }
1449    },
1450    US {
1451      TimeUnit unit() { return TimeUnit.MICROSECONDS; }
1452      String suffix() { return "us"; }
1453    },
1454    MS {
1455      TimeUnit unit() { return TimeUnit.MILLISECONDS; }
1456      String suffix() { return "ms"; }
1457    },
1458    S {
1459      TimeUnit unit() { return TimeUnit.SECONDS; }
1460      String suffix() { return "s"; }
1461    },
1462    M {
1463      TimeUnit unit() { return TimeUnit.MINUTES; }
1464      String suffix() { return "m"; }
1465    },
1466    H {
1467      TimeUnit unit() { return TimeUnit.HOURS; }
1468      String suffix() { return "h"; }
1469    },
1470    D {
1471      TimeUnit unit() { return TimeUnit.DAYS; }
1472      String suffix() { return "d"; }
1473    };
1474    abstract TimeUnit unit();
1475    abstract String suffix();
1476    static ParsedTimeDuration unitFor(String s) {
1477      for (ParsedTimeDuration ptd : values()) {
1478        // iteration order is in decl order, so SECONDS matched last
1479        if (s.endsWith(ptd.suffix())) {
1480          return ptd;
1481        }
1482      }
1483      return null;
1484    }
1485    static ParsedTimeDuration unitFor(TimeUnit unit) {
1486      for (ParsedTimeDuration ptd : values()) {
1487        if (ptd.unit() == unit) {
1488          return ptd;
1489        }
1490      }
1491      return null;
1492    }
1493  }
1494
1495  /**
1496   * Set the value of <code>name</code> to the given time duration. This
1497   * is equivalent to <code>set(&lt;name&gt;, value + &lt;time suffix&gt;)</code>.
1498   * @param name Property name
1499   * @param value Time duration
1500   * @param unit Unit of time
1501   */
1502  public void setTimeDuration(String name, long value, TimeUnit unit) {
1503    set(name, value + ParsedTimeDuration.unitFor(unit).suffix());
1504  }
1505
1506  /**
1507   * Return time duration in the given time unit. Valid units are encoded in
1508   * properties as suffixes: nanoseconds (ns), microseconds (us), milliseconds
1509   * (ms), seconds (s), minutes (m), hours (h), and days (d).
1510   * @param name Property name
1511   * @param defaultValue Value returned if no mapping exists.
1512   * @param unit Unit to convert the stored property, if it exists.
1513   * @throws NumberFormatException If the property stripped of its unit is not
1514   *         a number
1515   */
1516  public long getTimeDuration(String name, long defaultValue, TimeUnit unit) {
1517    String vStr = get(name);
1518    if (null == vStr) {
1519      return defaultValue;
1520    }
1521    vStr = vStr.trim();
1522    ParsedTimeDuration vUnit = ParsedTimeDuration.unitFor(vStr);
1523    if (null == vUnit) {
1524      LOG.warn("No unit for " + name + "(" + vStr + ") assuming " + unit);
1525      vUnit = ParsedTimeDuration.unitFor(unit);
1526    } else {
1527      vStr = vStr.substring(0, vStr.lastIndexOf(vUnit.suffix()));
1528    }
1529    return unit.convert(Long.parseLong(vStr), vUnit.unit());
1530  }
1531
1532  /**
1533   * Get the value of the <code>name</code> property as a <code>Pattern</code>.
1534   * If no such property is specified, or if the specified value is not a valid
1535   * <code>Pattern</code>, then <code>DefaultValue</code> is returned.
1536   *
1537   * @param name property name
1538   * @param defaultValue default value
1539   * @return property value as a compiled Pattern, or defaultValue
1540   */
1541  public Pattern getPattern(String name, Pattern defaultValue) {
1542    String valString = get(name);
1543    if (null == valString || valString.isEmpty()) {
1544      return defaultValue;
1545    }
1546    try {
1547      return Pattern.compile(valString);
1548    } catch (PatternSyntaxException pse) {
1549      LOG.warn("Regular expression '" + valString + "' for property '" +
1550               name + "' not valid. Using default", pse);
1551      return defaultValue;
1552    }
1553  }
1554
1555  /**
1556   * Set the given property to <code>Pattern</code>.
1557   * If the pattern is passed as null, sets the empty pattern which results in
1558   * further calls to getPattern(...) returning the default value.
1559   *
1560   * @param name property name
1561   * @param pattern new value
1562   */
1563  public void setPattern(String name, Pattern pattern) {
1564    if (null == pattern) {
1565      set(name, null);
1566    } else {
1567      set(name, pattern.pattern());
1568    }
1569  }
1570
1571  /**
1572   * Gets information about why a property was set.  Typically this is the 
1573   * path to the resource objects (file, URL, etc.) the property came from, but
1574   * it can also indicate that it was set programatically, or because of the
1575   * command line.
1576   *
1577   * @param name - The property name to get the source of.
1578   * @return null - If the property or its source wasn't found. Otherwise, 
1579   * returns a list of the sources of the resource.  The older sources are
1580   * the first ones in the list.  So for example if a configuration is set from
1581   * the command line, and then written out to a file that is read back in the
1582   * first entry would indicate that it was set from the command line, while
1583   * the second one would indicate the file that the new configuration was read
1584   * in from.
1585   */
1586  @InterfaceStability.Unstable
1587  public synchronized String[] getPropertySources(String name) {
1588    if (properties == null) {
1589      // If properties is null, it means a resource was newly added
1590      // but the props were cleared so as to load it upon future
1591      // requests. So lets force a load by asking a properties list.
1592      getProps();
1593    }
1594    // Return a null right away if our properties still
1595    // haven't loaded or the resource mapping isn't defined
1596    if (properties == null || updatingResource == null) {
1597      return null;
1598    } else {
1599      String[] source = updatingResource.get(name);
1600      if(source == null) {
1601        return null;
1602      } else {
1603        return Arrays.copyOf(source, source.length);
1604      }
1605    }
1606  }
1607
1608  /**
1609   * A class that represents a set of positive integer ranges. It parses 
1610   * strings of the form: "2-3,5,7-" where ranges are separated by comma and 
1611   * the lower/upper bounds are separated by dash. Either the lower or upper 
1612   * bound may be omitted meaning all values up to or over. So the string 
1613   * above means 2, 3, 5, and 7, 8, 9, ...
1614   */
1615  public static class IntegerRanges implements Iterable<Integer>{
1616    private static class Range {
1617      int start;
1618      int end;
1619    }
1620    
1621    private static class RangeNumberIterator implements Iterator<Integer> {
1622      Iterator<Range> internal;
1623      int at;
1624      int end;
1625
1626      public RangeNumberIterator(List<Range> ranges) {
1627        if (ranges != null) {
1628          internal = ranges.iterator();
1629        }
1630        at = -1;
1631        end = -2;
1632      }
1633      
1634      @Override
1635      public boolean hasNext() {
1636        if (at <= end) {
1637          return true;
1638        } else if (internal != null){
1639          return internal.hasNext();
1640        }
1641        return false;
1642      }
1643
1644      @Override
1645      public Integer next() {
1646        if (at <= end) {
1647          at++;
1648          return at - 1;
1649        } else if (internal != null){
1650          Range found = internal.next();
1651          if (found != null) {
1652            at = found.start;
1653            end = found.end;
1654            at++;
1655            return at - 1;
1656          }
1657        }
1658        return null;
1659      }
1660
1661      @Override
1662      public void remove() {
1663        throw new UnsupportedOperationException();
1664      }
1665    };
1666
1667    List<Range> ranges = new ArrayList<Range>();
1668    
1669    public IntegerRanges() {
1670    }
1671    
1672    public IntegerRanges(String newValue) {
1673      StringTokenizer itr = new StringTokenizer(newValue, ",");
1674      while (itr.hasMoreTokens()) {
1675        String rng = itr.nextToken().trim();
1676        String[] parts = rng.split("-", 3);
1677        if (parts.length < 1 || parts.length > 2) {
1678          throw new IllegalArgumentException("integer range badly formed: " + 
1679                                             rng);
1680        }
1681        Range r = new Range();
1682        r.start = convertToInt(parts[0], 0);
1683        if (parts.length == 2) {
1684          r.end = convertToInt(parts[1], Integer.MAX_VALUE);
1685        } else {
1686          r.end = r.start;
1687        }
1688        if (r.start > r.end) {
1689          throw new IllegalArgumentException("IntegerRange from " + r.start + 
1690                                             " to " + r.end + " is invalid");
1691        }
1692        ranges.add(r);
1693      }
1694    }
1695
1696    /**
1697     * Convert a string to an int treating empty strings as the default value.
1698     * @param value the string value
1699     * @param defaultValue the value for if the string is empty
1700     * @return the desired integer
1701     */
1702    private static int convertToInt(String value, int defaultValue) {
1703      String trim = value.trim();
1704      if (trim.length() == 0) {
1705        return defaultValue;
1706      }
1707      return Integer.parseInt(trim);
1708    }
1709
1710    /**
1711     * Is the given value in the set of ranges
1712     * @param value the value to check
1713     * @return is the value in the ranges?
1714     */
1715    public boolean isIncluded(int value) {
1716      for(Range r: ranges) {
1717        if (r.start <= value && value <= r.end) {
1718          return true;
1719        }
1720      }
1721      return false;
1722    }
1723    
1724    /**
1725     * @return true if there are no values in this range, else false.
1726     */
1727    public boolean isEmpty() {
1728      return ranges == null || ranges.isEmpty();
1729    }
1730    
1731    @Override
1732    public String toString() {
1733      StringBuilder result = new StringBuilder();
1734      boolean first = true;
1735      for(Range r: ranges) {
1736        if (first) {
1737          first = false;
1738        } else {
1739          result.append(',');
1740        }
1741        result.append(r.start);
1742        result.append('-');
1743        result.append(r.end);
1744      }
1745      return result.toString();
1746    }
1747
1748    @Override
1749    public Iterator<Integer> iterator() {
1750      return new RangeNumberIterator(ranges);
1751    }
1752    
1753  }
1754
1755  /**
1756   * Parse the given attribute as a set of integer ranges
1757   * @param name the attribute name
1758   * @param defaultValue the default value if it is not set
1759   * @return a new set of ranges from the configured value
1760   */
1761  public IntegerRanges getRange(String name, String defaultValue) {
1762    return new IntegerRanges(get(name, defaultValue));
1763  }
1764
1765  /** 
1766   * Get the comma delimited values of the <code>name</code> property as 
1767   * a collection of <code>String</code>s.  
1768   * If no such property is specified then empty collection is returned.
1769   * <p>
1770   * This is an optimized version of {@link #getStrings(String)}
1771   * 
1772   * @param name property name.
1773   * @return property value as a collection of <code>String</code>s. 
1774   */
1775  public Collection<String> getStringCollection(String name) {
1776    String valueString = get(name);
1777    return StringUtils.getStringCollection(valueString);
1778  }
1779
1780  /** 
1781   * Get the comma delimited values of the <code>name</code> property as 
1782   * an array of <code>String</code>s.  
1783   * If no such property is specified then <code>null</code> is returned.
1784   * 
1785   * @param name property name.
1786   * @return property value as an array of <code>String</code>s, 
1787   *         or <code>null</code>. 
1788   */
1789  public String[] getStrings(String name) {
1790    String valueString = get(name);
1791    return StringUtils.getStrings(valueString);
1792  }
1793
1794  /** 
1795   * Get the comma delimited values of the <code>name</code> property as 
1796   * an array of <code>String</code>s.  
1797   * If no such property is specified then default value is returned.
1798   * 
1799   * @param name property name.
1800   * @param defaultValue The default value
1801   * @return property value as an array of <code>String</code>s, 
1802   *         or default value. 
1803   */
1804  public String[] getStrings(String name, String... defaultValue) {
1805    String valueString = get(name);
1806    if (valueString == null) {
1807      return defaultValue;
1808    } else {
1809      return StringUtils.getStrings(valueString);
1810    }
1811  }
1812  
1813  /** 
1814   * Get the comma delimited values of the <code>name</code> property as 
1815   * a collection of <code>String</code>s, trimmed of the leading and trailing whitespace.  
1816   * If no such property is specified then empty <code>Collection</code> is returned.
1817   *
1818   * @param name property name.
1819   * @return property value as a collection of <code>String</code>s, or empty <code>Collection</code> 
1820   */
1821  public Collection<String> getTrimmedStringCollection(String name) {
1822    String valueString = get(name);
1823    if (null == valueString) {
1824      Collection<String> empty = new ArrayList<String>();
1825      return empty;
1826    }
1827    return StringUtils.getTrimmedStringCollection(valueString);
1828  }
1829  
1830  /** 
1831   * Get the comma delimited values of the <code>name</code> property as 
1832   * an array of <code>String</code>s, trimmed of the leading and trailing whitespace.
1833   * If no such property is specified then an empty array is returned.
1834   * 
1835   * @param name property name.
1836   * @return property value as an array of trimmed <code>String</code>s, 
1837   *         or empty array. 
1838   */
1839  public String[] getTrimmedStrings(String name) {
1840    String valueString = get(name);
1841    return StringUtils.getTrimmedStrings(valueString);
1842  }
1843
1844  /** 
1845   * Get the comma delimited values of the <code>name</code> property as 
1846   * an array of <code>String</code>s, trimmed of the leading and trailing whitespace.
1847   * If no such property is specified then default value is returned.
1848   * 
1849   * @param name property name.
1850   * @param defaultValue The default value
1851   * @return property value as an array of trimmed <code>String</code>s, 
1852   *         or default value. 
1853   */
1854  public String[] getTrimmedStrings(String name, String... defaultValue) {
1855    String valueString = get(name);
1856    if (null == valueString) {
1857      return defaultValue;
1858    } else {
1859      return StringUtils.getTrimmedStrings(valueString);
1860    }
1861  }
1862
1863  /** 
1864   * Set the array of string values for the <code>name</code> property as 
1865   * as comma delimited values.  
1866   * 
1867   * @param name property name.
1868   * @param values The values
1869   */
1870  public void setStrings(String name, String... values) {
1871    set(name, StringUtils.arrayToString(values));
1872  }
1873
1874  /**
1875   * Get the value for a known password configuration element.
1876   * In order to enable the elimination of clear text passwords in config,
1877   * this method attempts to resolve the property name as an alias through
1878   * the CredentialProvider API and conditionally fallsback to config.
1879   * @param name property name
1880   * @return password
1881   */
1882  public char[] getPassword(String name) throws IOException {
1883    char[] pass = null;
1884
1885    pass = getPasswordFromCredentialProviders(name);
1886
1887    if (pass == null) {
1888      pass = getPasswordFromConfig(name);
1889    }
1890
1891    return pass;
1892  }
1893
1894  /**
1895   * Try and resolve the provided element name as a credential provider
1896   * alias.
1897   * @param name alias of the provisioned credential
1898   * @return password or null if not found
1899   * @throws IOException
1900   */
1901  protected char[] getPasswordFromCredentialProviders(String name)
1902      throws IOException {
1903    char[] pass = null;
1904    try {
1905      List<CredentialProvider> providers =
1906          CredentialProviderFactory.getProviders(this);
1907
1908      if (providers != null) {
1909        for (CredentialProvider provider : providers) {
1910          try {
1911            CredentialEntry entry = provider.getCredentialEntry(name);
1912            if (entry != null) {
1913              pass = entry.getCredential();
1914              break;
1915            }
1916          }
1917          catch (IOException ioe) {
1918            throw new IOException("Can't get key " + name + " from key provider" +
1919                        "of type: " + provider.getClass().getName() + ".", ioe);
1920          }
1921        }
1922      }
1923    }
1924    catch (IOException ioe) {
1925      throw new IOException("Configuration problem with provider path.", ioe);
1926    }
1927
1928    return pass;
1929  }
1930
1931  /**
1932   * Fallback to clear text passwords in configuration.
1933   * @param name
1934   * @return clear text password or null
1935   */
1936  protected char[] getPasswordFromConfig(String name) {
1937    char[] pass = null;
1938    if (getBoolean(CredentialProvider.CLEAR_TEXT_FALLBACK, true)) {
1939      String passStr = get(name);
1940      if (passStr != null) {
1941        pass = passStr.toCharArray();
1942      }
1943    }
1944    return pass;
1945  }
1946
1947  /**
1948   * Get the socket address for <code>hostProperty</code> as a
1949   * <code>InetSocketAddress</code>. If <code>hostProperty</code> is
1950   * <code>null</code>, <code>addressProperty</code> will be used. This
1951   * is useful for cases where we want to differentiate between host
1952   * bind address and address clients should use to establish connection.
1953   *
1954   * @param hostProperty bind host property name.
1955   * @param addressProperty address property name.
1956   * @param defaultAddressValue the default value
1957   * @param defaultPort the default port
1958   * @return InetSocketAddress
1959   */
1960  public InetSocketAddress getSocketAddr(
1961      String hostProperty,
1962      String addressProperty,
1963      String defaultAddressValue,
1964      int defaultPort) {
1965
1966    InetSocketAddress bindAddr = getSocketAddr(
1967      addressProperty, defaultAddressValue, defaultPort);
1968
1969    final String host = get(hostProperty);
1970
1971    if (host == null || host.isEmpty()) {
1972      return bindAddr;
1973    }
1974
1975    return NetUtils.createSocketAddr(
1976        host, bindAddr.getPort(), hostProperty);
1977  }
1978
1979  /**
1980   * Get the socket address for <code>name</code> property as a
1981   * <code>InetSocketAddress</code>.
1982   * @param name property name.
1983   * @param defaultAddress the default value
1984   * @param defaultPort the default port
1985   * @return InetSocketAddress
1986   */
1987  public InetSocketAddress getSocketAddr(
1988      String name, String defaultAddress, int defaultPort) {
1989    final String address = get(name, defaultAddress);
1990    return NetUtils.createSocketAddr(address, defaultPort, name);
1991  }
1992
1993  /**
1994   * Set the socket address for the <code>name</code> property as
1995   * a <code>host:port</code>.
1996   */
1997  public void setSocketAddr(String name, InetSocketAddress addr) {
1998    set(name, NetUtils.getHostPortString(addr));
1999  }
2000
2001  /**
2002   * Set the socket address a client can use to connect for the
2003   * <code>name</code> property as a <code>host:port</code>.  The wildcard
2004   * address is replaced with the local host's address. If the host and address
2005   * properties are configured the host component of the address will be combined
2006   * with the port component of the addr to generate the address.  This is to allow
2007   * optional control over which host name is used in multi-home bind-host
2008   * cases where a host can have multiple names
2009   * @param hostProperty the bind-host configuration name
2010   * @param addressProperty the service address configuration name
2011   * @param defaultAddressValue the service default address configuration value
2012   * @param addr InetSocketAddress of the service listener
2013   * @return InetSocketAddress for clients to connect
2014   */
2015  public InetSocketAddress updateConnectAddr(
2016      String hostProperty,
2017      String addressProperty,
2018      String defaultAddressValue,
2019      InetSocketAddress addr) {
2020
2021    final String host = get(hostProperty);
2022    final String connectHostPort = getTrimmed(addressProperty, defaultAddressValue);
2023
2024    if (host == null || host.isEmpty() || connectHostPort == null || connectHostPort.isEmpty()) {
2025      //not our case, fall back to original logic
2026      return updateConnectAddr(addressProperty, addr);
2027    }
2028
2029    final String connectHost = connectHostPort.split(":")[0];
2030    // Create connect address using client address hostname and server port.
2031    return updateConnectAddr(addressProperty, NetUtils.createSocketAddrForHost(
2032        connectHost, addr.getPort()));
2033  }
2034  
2035  /**
2036   * Set the socket address a client can use to connect for the
2037   * <code>name</code> property as a <code>host:port</code>.  The wildcard
2038   * address is replaced with the local host's address.
2039   * @param name property name.
2040   * @param addr InetSocketAddress of a listener to store in the given property
2041   * @return InetSocketAddress for clients to connect
2042   */
2043  public InetSocketAddress updateConnectAddr(String name,
2044                                             InetSocketAddress addr) {
2045    final InetSocketAddress connectAddr = NetUtils.getConnectAddress(addr);
2046    setSocketAddr(name, connectAddr);
2047    return connectAddr;
2048  }
2049  
2050  /**
2051   * Load a class by name.
2052   * 
2053   * @param name the class name.
2054   * @return the class object.
2055   * @throws ClassNotFoundException if the class is not found.
2056   */
2057  public Class<?> getClassByName(String name) throws ClassNotFoundException {
2058    Class<?> ret = getClassByNameOrNull(name);
2059    if (ret == null) {
2060      throw new ClassNotFoundException("Class " + name + " not found");
2061    }
2062    return ret;
2063  }
2064  
2065  /**
2066   * Load a class by name, returning null rather than throwing an exception
2067   * if it couldn't be loaded. This is to avoid the overhead of creating
2068   * an exception.
2069   * 
2070   * @param name the class name
2071   * @return the class object, or null if it could not be found.
2072   */
2073  public Class<?> getClassByNameOrNull(String name) {
2074    Map<String, WeakReference<Class<?>>> map;
2075    
2076    synchronized (CACHE_CLASSES) {
2077      map = CACHE_CLASSES.get(classLoader);
2078      if (map == null) {
2079        map = Collections.synchronizedMap(
2080          new WeakHashMap<String, WeakReference<Class<?>>>());
2081        CACHE_CLASSES.put(classLoader, map);
2082      }
2083    }
2084
2085    Class<?> clazz = null;
2086    WeakReference<Class<?>> ref = map.get(name); 
2087    if (ref != null) {
2088       clazz = ref.get();
2089    }
2090     
2091    if (clazz == null) {
2092      try {
2093        clazz = Class.forName(name, true, classLoader);
2094      } catch (ClassNotFoundException e) {
2095        // Leave a marker that the class isn't found
2096        map.put(name, new WeakReference<Class<?>>(NEGATIVE_CACHE_SENTINEL));
2097        return null;
2098      }
2099      // two putters can race here, but they'll put the same class
2100      map.put(name, new WeakReference<Class<?>>(clazz));
2101      return clazz;
2102    } else if (clazz == NEGATIVE_CACHE_SENTINEL) {
2103      return null; // not found
2104    } else {
2105      // cache hit
2106      return clazz;
2107    }
2108  }
2109
2110  /** 
2111   * Get the value of the <code>name</code> property
2112   * as an array of <code>Class</code>.
2113   * The value of the property specifies a list of comma separated class names.  
2114   * If no such property is specified, then <code>defaultValue</code> is 
2115   * returned.
2116   * 
2117   * @param name the property name.
2118   * @param defaultValue default value.
2119   * @return property value as a <code>Class[]</code>, 
2120   *         or <code>defaultValue</code>. 
2121   */
2122  public Class<?>[] getClasses(String name, Class<?> ... defaultValue) {
2123    String[] classnames = getTrimmedStrings(name);
2124    if (classnames == null)
2125      return defaultValue;
2126    try {
2127      Class<?>[] classes = new Class<?>[classnames.length];
2128      for(int i = 0; i < classnames.length; i++) {
2129        classes[i] = getClassByName(classnames[i]);
2130      }
2131      return classes;
2132    } catch (ClassNotFoundException e) {
2133      throw new RuntimeException(e);
2134    }
2135  }
2136
2137  /** 
2138   * Get the value of the <code>name</code> property as a <code>Class</code>.  
2139   * If no such property is specified, then <code>defaultValue</code> is 
2140   * returned.
2141   * 
2142   * @param name the class name.
2143   * @param defaultValue default value.
2144   * @return property value as a <code>Class</code>, 
2145   *         or <code>defaultValue</code>. 
2146   */
2147  public Class<?> getClass(String name, Class<?> defaultValue) {
2148    String valueString = getTrimmed(name);
2149    if (valueString == null)
2150      return defaultValue;
2151    try {
2152      return getClassByName(valueString);
2153    } catch (ClassNotFoundException e) {
2154      throw new RuntimeException(e);
2155    }
2156  }
2157
2158  /** 
2159   * Get the value of the <code>name</code> property as a <code>Class</code>
2160   * implementing the interface specified by <code>xface</code>.
2161   *   
2162   * If no such property is specified, then <code>defaultValue</code> is 
2163   * returned.
2164   * 
2165   * An exception is thrown if the returned class does not implement the named
2166   * interface. 
2167   * 
2168   * @param name the class name.
2169   * @param defaultValue default value.
2170   * @param xface the interface implemented by the named class.
2171   * @return property value as a <code>Class</code>, 
2172   *         or <code>defaultValue</code>.
2173   */
2174  public <U> Class<? extends U> getClass(String name, 
2175                                         Class<? extends U> defaultValue, 
2176                                         Class<U> xface) {
2177    try {
2178      Class<?> theClass = getClass(name, defaultValue);
2179      if (theClass != null && !xface.isAssignableFrom(theClass))
2180        throw new RuntimeException(theClass+" not "+xface.getName());
2181      else if (theClass != null)
2182        return theClass.asSubclass(xface);
2183      else
2184        return null;
2185    } catch (Exception e) {
2186      throw new RuntimeException(e);
2187    }
2188  }
2189
2190  /**
2191   * Get the value of the <code>name</code> property as a <code>List</code>
2192   * of objects implementing the interface specified by <code>xface</code>.
2193   * 
2194   * An exception is thrown if any of the classes does not exist, or if it does
2195   * not implement the named interface.
2196   * 
2197   * @param name the property name.
2198   * @param xface the interface implemented by the classes named by
2199   *        <code>name</code>.
2200   * @return a <code>List</code> of objects implementing <code>xface</code>.
2201   */
2202  @SuppressWarnings("unchecked")
2203  public <U> List<U> getInstances(String name, Class<U> xface) {
2204    List<U> ret = new ArrayList<U>();
2205    Class<?>[] classes = getClasses(name);
2206    for (Class<?> cl: classes) {
2207      if (!xface.isAssignableFrom(cl)) {
2208        throw new RuntimeException(cl + " does not implement " + xface);
2209      }
2210      ret.add((U)ReflectionUtils.newInstance(cl, this));
2211    }
2212    return ret;
2213  }
2214
2215  /** 
2216   * Set the value of the <code>name</code> property to the name of a 
2217   * <code>theClass</code> implementing the given interface <code>xface</code>.
2218   * 
2219   * An exception is thrown if <code>theClass</code> does not implement the 
2220   * interface <code>xface</code>. 
2221   * 
2222   * @param name property name.
2223   * @param theClass property value.
2224   * @param xface the interface implemented by the named class.
2225   */
2226  public void setClass(String name, Class<?> theClass, Class<?> xface) {
2227    if (!xface.isAssignableFrom(theClass))
2228      throw new RuntimeException(theClass+" not "+xface.getName());
2229    set(name, theClass.getName());
2230  }
2231
2232  /** 
2233   * Get a local file under a directory named by <i>dirsProp</i> with
2234   * the given <i>path</i>.  If <i>dirsProp</i> contains multiple directories,
2235   * then one is chosen based on <i>path</i>'s hash code.  If the selected
2236   * directory does not exist, an attempt is made to create it.
2237   * 
2238   * @param dirsProp directory in which to locate the file.
2239   * @param path file-path.
2240   * @return local file under the directory with the given path.
2241   */
2242  public Path getLocalPath(String dirsProp, String path)
2243    throws IOException {
2244    String[] dirs = getTrimmedStrings(dirsProp);
2245    int hashCode = path.hashCode();
2246    FileSystem fs = FileSystem.getLocal(this);
2247    for (int i = 0; i < dirs.length; i++) {  // try each local dir
2248      int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
2249      Path file = new Path(dirs[index], path);
2250      Path dir = file.getParent();
2251      if (fs.mkdirs(dir) || fs.exists(dir)) {
2252        return file;
2253      }
2254    }
2255    LOG.warn("Could not make " + path + 
2256             " in local directories from " + dirsProp);
2257    for(int i=0; i < dirs.length; i++) {
2258      int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
2259      LOG.warn(dirsProp + "[" + index + "]=" + dirs[index]);
2260    }
2261    throw new IOException("No valid local directories in property: "+dirsProp);
2262  }
2263
2264  /** 
2265   * Get a local file name under a directory named in <i>dirsProp</i> with
2266   * the given <i>path</i>.  If <i>dirsProp</i> contains multiple directories,
2267   * then one is chosen based on <i>path</i>'s hash code.  If the selected
2268   * directory does not exist, an attempt is made to create it.
2269   * 
2270   * @param dirsProp directory in which to locate the file.
2271   * @param path file-path.
2272   * @return local file under the directory with the given path.
2273   */
2274  public File getFile(String dirsProp, String path)
2275    throws IOException {
2276    String[] dirs = getTrimmedStrings(dirsProp);
2277    int hashCode = path.hashCode();
2278    for (int i = 0; i < dirs.length; i++) {  // try each local dir
2279      int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
2280      File file = new File(dirs[index], path);
2281      File dir = file.getParentFile();
2282      if (dir.exists() || dir.mkdirs()) {
2283        return file;
2284      }
2285    }
2286    throw new IOException("No valid local directories in property: "+dirsProp);
2287  }
2288
2289  /** 
2290   * Get the {@link URL} for the named resource.
2291   * 
2292   * @param name resource name.
2293   * @return the url for the named resource.
2294   */
2295  public URL getResource(String name) {
2296    return classLoader.getResource(name);
2297  }
2298  
2299  /** 
2300   * Get an input stream attached to the configuration resource with the
2301   * given <code>name</code>.
2302   * 
2303   * @param name configuration resource name.
2304   * @return an input stream attached to the resource.
2305   */
2306  public InputStream getConfResourceAsInputStream(String name) {
2307    try {
2308      URL url= getResource(name);
2309
2310      if (url == null) {
2311        LOG.info(name + " not found");
2312        return null;
2313      } else {
2314        LOG.info("found resource " + name + " at " + url);
2315      }
2316
2317      return url.openStream();
2318    } catch (Exception e) {
2319      return null;
2320    }
2321  }
2322
2323  /** 
2324   * Get a {@link Reader} attached to the configuration resource with the
2325   * given <code>name</code>.
2326   * 
2327   * @param name configuration resource name.
2328   * @return a reader attached to the resource.
2329   */
2330  public Reader getConfResourceAsReader(String name) {
2331    try {
2332      URL url= getResource(name);
2333
2334      if (url == null) {
2335        LOG.info(name + " not found");
2336        return null;
2337      } else {
2338        LOG.info("found resource " + name + " at " + url);
2339      }
2340
2341      return new InputStreamReader(url.openStream());
2342    } catch (Exception e) {
2343      return null;
2344    }
2345  }
2346
2347  /**
2348   * Get the set of parameters marked final.
2349   *
2350   * @return final parameter set.
2351   */
2352  public Set<String> getFinalParameters() {
2353    return new HashSet<String>(finalParameters);
2354  }
2355
2356  protected synchronized Properties getProps() {
2357    if (properties == null) {
2358      properties = new Properties();
2359      HashMap<String, String[]> backup = 
2360        new HashMap<String, String[]>(updatingResource);
2361      loadResources(properties, resources, quietmode);
2362      if (overlay!= null) {
2363        properties.putAll(overlay);
2364        for (Map.Entry<Object,Object> item: overlay.entrySet()) {
2365          String key = (String)item.getKey();
2366          updatingResource.put(key, backup.get(key));
2367        }
2368      }
2369    }
2370    return properties;
2371  }
2372
2373  /**
2374   * Return the number of keys in the configuration.
2375   *
2376   * @return number of keys in the configuration.
2377   */
2378  public int size() {
2379    return getProps().size();
2380  }
2381
2382  /**
2383   * Clears all keys from the configuration.
2384   */
2385  public void clear() {
2386    getProps().clear();
2387    getOverlay().clear();
2388  }
2389
2390  /**
2391   * Get an {@link Iterator} to go through the list of <code>String</code> 
2392   * key-value pairs in the configuration.
2393   * 
2394   * @return an iterator over the entries.
2395   */
2396  @Override
2397  public Iterator<Map.Entry<String, String>> iterator() {
2398    // Get a copy of just the string to string pairs. After the old object
2399    // methods that allow non-strings to be put into configurations are removed,
2400    // we could replace properties with a Map<String,String> and get rid of this
2401    // code.
2402    Map<String,String> result = new HashMap<String,String>();
2403    for(Map.Entry<Object,Object> item: getProps().entrySet()) {
2404      if (item.getKey() instanceof String && 
2405          item.getValue() instanceof String) {
2406        result.put((String) item.getKey(), (String) item.getValue());
2407      }
2408    }
2409    return result.entrySet().iterator();
2410  }
2411
2412  private Document parse(DocumentBuilder builder, URL url)
2413      throws IOException, SAXException {
2414    if (!quietmode) {
2415      LOG.debug("parsing URL " + url);
2416    }
2417    if (url == null) {
2418      return null;
2419    }
2420    return parse(builder, url.openStream(), url.toString());
2421  }
2422
2423  private Document parse(DocumentBuilder builder, InputStream is,
2424      String systemId) throws IOException, SAXException {
2425    if (!quietmode) {
2426      LOG.debug("parsing input stream " + is);
2427    }
2428    if (is == null) {
2429      return null;
2430    }
2431    try {
2432      return (systemId == null) ? builder.parse(is) : builder.parse(is,
2433          systemId);
2434    } finally {
2435      is.close();
2436    }
2437  }
2438
2439  private void loadResources(Properties properties,
2440                             ArrayList<Resource> resources,
2441                             boolean quiet) {
2442    if(loadDefaults) {
2443      for (String resource : defaultResources) {
2444        loadResource(properties, new Resource(resource), quiet);
2445      }
2446    
2447      //support the hadoop-site.xml as a deprecated case
2448      if(getResource("hadoop-site.xml")!=null) {
2449        loadResource(properties, new Resource("hadoop-site.xml"), quiet);
2450      }
2451    }
2452    
2453    for (int i = 0; i < resources.size(); i++) {
2454      Resource ret = loadResource(properties, resources.get(i), quiet);
2455      if (ret != null) {
2456        resources.set(i, ret);
2457      }
2458    }
2459  }
2460  
2461  private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) {
2462    String name = UNKNOWN_RESOURCE;
2463    try {
2464      Object resource = wrapper.getResource();
2465      name = wrapper.getName();
2466      
2467      DocumentBuilderFactory docBuilderFactory 
2468        = DocumentBuilderFactory.newInstance();
2469      //ignore all comments inside the xml file
2470      docBuilderFactory.setIgnoringComments(true);
2471
2472      //allow includes in the xml file
2473      docBuilderFactory.setNamespaceAware(true);
2474      try {
2475          docBuilderFactory.setXIncludeAware(true);
2476      } catch (UnsupportedOperationException e) {
2477        LOG.error("Failed to set setXIncludeAware(true) for parser "
2478                + docBuilderFactory
2479                + ":" + e,
2480                e);
2481      }
2482      DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
2483      Document doc = null;
2484      Element root = null;
2485      boolean returnCachedProperties = false;
2486      
2487      if (resource instanceof URL) {                  // an URL resource
2488        doc = parse(builder, (URL)resource);
2489      } else if (resource instanceof String) {        // a CLASSPATH resource
2490        URL url = getResource((String)resource);
2491        doc = parse(builder, url);
2492      } else if (resource instanceof Path) {          // a file resource
2493        // Can't use FileSystem API or we get an infinite loop
2494        // since FileSystem uses Configuration API.  Use java.io.File instead.
2495        File file = new File(((Path)resource).toUri().getPath())
2496          .getAbsoluteFile();
2497        if (file.exists()) {
2498          if (!quiet) {
2499            LOG.debug("parsing File " + file);
2500          }
2501          doc = parse(builder, new BufferedInputStream(
2502              new FileInputStream(file)), ((Path)resource).toString());
2503        }
2504      } else if (resource instanceof InputStream) {
2505        doc = parse(builder, (InputStream) resource, null);
2506        returnCachedProperties = true;
2507      } else if (resource instanceof Properties) {
2508        overlay(properties, (Properties)resource);
2509      } else if (resource instanceof Element) {
2510        root = (Element)resource;
2511      }
2512
2513      if (root == null) {
2514        if (doc == null) {
2515          if (quiet) {
2516            return null;
2517          }
2518          throw new RuntimeException(resource + " not found");
2519        }
2520        root = doc.getDocumentElement();
2521      }
2522      Properties toAddTo = properties;
2523      if(returnCachedProperties) {
2524        toAddTo = new Properties();
2525      }
2526      if (!"configuration".equals(root.getTagName()))
2527        LOG.fatal("bad conf file: top-level element not <configuration>");
2528      NodeList props = root.getChildNodes();
2529      DeprecationContext deprecations = deprecationContext.get();
2530      for (int i = 0; i < props.getLength(); i++) {
2531        Node propNode = props.item(i);
2532        if (!(propNode instanceof Element))
2533          continue;
2534        Element prop = (Element)propNode;
2535        if ("configuration".equals(prop.getTagName())) {
2536          loadResource(toAddTo, new Resource(prop, name), quiet);
2537          continue;
2538        }
2539        if (!"property".equals(prop.getTagName()))
2540          LOG.warn("bad conf file: element not <property>");
2541        NodeList fields = prop.getChildNodes();
2542        String attr = null;
2543        String value = null;
2544        boolean finalParameter = false;
2545        LinkedList<String> source = new LinkedList<String>();
2546        for (int j = 0; j < fields.getLength(); j++) {
2547          Node fieldNode = fields.item(j);
2548          if (!(fieldNode instanceof Element))
2549            continue;
2550          Element field = (Element)fieldNode;
2551          if ("name".equals(field.getTagName()) && field.hasChildNodes())
2552            attr = StringInterner.weakIntern(
2553                ((Text)field.getFirstChild()).getData().trim());
2554          if ("value".equals(field.getTagName()) && field.hasChildNodes())
2555            value = StringInterner.weakIntern(
2556                ((Text)field.getFirstChild()).getData());
2557          if ("final".equals(field.getTagName()) && field.hasChildNodes())
2558            finalParameter = "true".equals(((Text)field.getFirstChild()).getData());
2559          if ("source".equals(field.getTagName()) && field.hasChildNodes())
2560            source.add(StringInterner.weakIntern(
2561                ((Text)field.getFirstChild()).getData()));
2562        }
2563        source.add(name);
2564        
2565        // Ignore this parameter if it has already been marked as 'final'
2566        if (attr != null) {
2567          if (deprecations.getDeprecatedKeyMap().containsKey(attr)) {
2568            DeprecatedKeyInfo keyInfo =
2569                deprecations.getDeprecatedKeyMap().get(attr);
2570            keyInfo.clearAccessed();
2571            for (String key:keyInfo.newKeys) {
2572              // update new keys with deprecated key's value 
2573              loadProperty(toAddTo, name, key, value, finalParameter, 
2574                  source.toArray(new String[source.size()]));
2575            }
2576          }
2577          else {
2578            loadProperty(toAddTo, name, attr, value, finalParameter, 
2579                source.toArray(new String[source.size()]));
2580          }
2581        }
2582      }
2583      
2584      if (returnCachedProperties) {
2585        overlay(properties, toAddTo);
2586        return new Resource(toAddTo, name);
2587      }
2588      return null;
2589    } catch (IOException e) {
2590      LOG.fatal("error parsing conf " + name, e);
2591      throw new RuntimeException(e);
2592    } catch (DOMException e) {
2593      LOG.fatal("error parsing conf " + name, e);
2594      throw new RuntimeException(e);
2595    } catch (SAXException e) {
2596      LOG.fatal("error parsing conf " + name, e);
2597      throw new RuntimeException(e);
2598    } catch (ParserConfigurationException e) {
2599      LOG.fatal("error parsing conf " + name , e);
2600      throw new RuntimeException(e);
2601    }
2602  }
2603
2604  private void overlay(Properties to, Properties from) {
2605    for (Entry<Object, Object> entry: from.entrySet()) {
2606      to.put(entry.getKey(), entry.getValue());
2607    }
2608  }
2609  
2610  private void loadProperty(Properties properties, String name, String attr,
2611      String value, boolean finalParameter, String[] source) {
2612    if (value != null) {
2613      if (!finalParameters.contains(attr)) {
2614        properties.setProperty(attr, value);
2615        updatingResource.put(attr, source);
2616      } else if (!value.equals(properties.getProperty(attr))) {
2617        LOG.warn(name+":an attempt to override final parameter: "+attr
2618            +";  Ignoring.");
2619      }
2620    }
2621    if (finalParameter) {
2622      finalParameters.add(attr);
2623    }
2624  }
2625
2626  /** 
2627   * Write out the non-default properties in this configuration to the given
2628   * {@link OutputStream} using UTF-8 encoding.
2629   * 
2630   * @param out the output stream to write to.
2631   */
2632  public void writeXml(OutputStream out) throws IOException {
2633    writeXml(new OutputStreamWriter(out, "UTF-8"));
2634  }
2635
2636  /** 
2637   * Write out the non-default properties in this configuration to the given
2638   * {@link Writer}.
2639   * 
2640   * @param out the writer to write to.
2641   */
2642  public void writeXml(Writer out) throws IOException {
2643    Document doc = asXmlDocument();
2644
2645    try {
2646      DOMSource source = new DOMSource(doc);
2647      StreamResult result = new StreamResult(out);
2648      TransformerFactory transFactory = TransformerFactory.newInstance();
2649      Transformer transformer = transFactory.newTransformer();
2650
2651      // Important to not hold Configuration log while writing result, since
2652      // 'out' may be an HDFS stream which needs to lock this configuration
2653      // from another thread.
2654      transformer.transform(source, result);
2655    } catch (TransformerException te) {
2656      throw new IOException(te);
2657    }
2658  }
2659
2660  /**
2661   * Return the XML DOM corresponding to this Configuration.
2662   */
2663  private synchronized Document asXmlDocument() throws IOException {
2664    Document doc;
2665    try {
2666      doc =
2667        DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
2668    } catch (ParserConfigurationException pe) {
2669      throw new IOException(pe);
2670    }
2671    Element conf = doc.createElement("configuration");
2672    doc.appendChild(conf);
2673    conf.appendChild(doc.createTextNode("\n"));
2674    handleDeprecation(); //ensure properties is set and deprecation is handled
2675    for (Enumeration<Object> e = properties.keys(); e.hasMoreElements();) {
2676      String name = (String)e.nextElement();
2677      Object object = properties.get(name);
2678      String value = null;
2679      if (object instanceof String) {
2680        value = (String) object;
2681      }else {
2682        continue;
2683      }
2684      Element propNode = doc.createElement("property");
2685      conf.appendChild(propNode);
2686
2687      Element nameNode = doc.createElement("name");
2688      nameNode.appendChild(doc.createTextNode(name));
2689      propNode.appendChild(nameNode);
2690
2691      Element valueNode = doc.createElement("value");
2692      valueNode.appendChild(doc.createTextNode(value));
2693      propNode.appendChild(valueNode);
2694
2695      if (updatingResource != null) {
2696        String[] sources = updatingResource.get(name);
2697        if(sources != null) {
2698          for(String s : sources) {
2699            Element sourceNode = doc.createElement("source");
2700            sourceNode.appendChild(doc.createTextNode(s));
2701            propNode.appendChild(sourceNode);
2702          }
2703        }
2704      }
2705      
2706      conf.appendChild(doc.createTextNode("\n"));
2707    }
2708    return doc;
2709  }
2710
2711  /**
2712   *  Writes out all the parameters and their properties (final and resource) to
2713   *  the given {@link Writer}
2714   *  The format of the output would be 
2715   *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
2716   *  key2.isFinal,key2.resource}... ] } 
2717   *  It does not output the parameters of the configuration object which is 
2718   *  loaded from an input stream.
2719   * @param out the Writer to write to
2720   * @throws IOException
2721   */
2722  public static void dumpConfiguration(Configuration config,
2723      Writer out) throws IOException {
2724    JsonFactory dumpFactory = new JsonFactory();
2725    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
2726    dumpGenerator.writeStartObject();
2727    dumpGenerator.writeFieldName("properties");
2728    dumpGenerator.writeStartArray();
2729    dumpGenerator.flush();
2730    synchronized (config) {
2731      for (Map.Entry<Object,Object> item: config.getProps().entrySet()) {
2732        dumpGenerator.writeStartObject();
2733        dumpGenerator.writeStringField("key", (String) item.getKey());
2734        dumpGenerator.writeStringField("value", 
2735                                       config.get((String) item.getKey()));
2736        dumpGenerator.writeBooleanField("isFinal",
2737                                        config.finalParameters.contains(item.getKey()));
2738        String[] resources = config.updatingResource.get(item.getKey());
2739        String resource = UNKNOWN_RESOURCE;
2740        if(resources != null && resources.length > 0) {
2741          resource = resources[0];
2742        }
2743        dumpGenerator.writeStringField("resource", resource);
2744        dumpGenerator.writeEndObject();
2745      }
2746    }
2747    dumpGenerator.writeEndArray();
2748    dumpGenerator.writeEndObject();
2749    dumpGenerator.flush();
2750  }
2751  
2752  /**
2753   * Get the {@link ClassLoader} for this job.
2754   * 
2755   * @return the correct class loader.
2756   */
2757  public ClassLoader getClassLoader() {
2758    return classLoader;
2759  }
2760  
2761  /**
2762   * Set the class loader that will be used to load the various objects.
2763   * 
2764   * @param classLoader the new class loader.
2765   */
2766  public void setClassLoader(ClassLoader classLoader) {
2767    this.classLoader = classLoader;
2768  }
2769  
2770  @Override
2771  public String toString() {
2772    StringBuilder sb = new StringBuilder();
2773    sb.append("Configuration: ");
2774    if(loadDefaults) {
2775      toString(defaultResources, sb);
2776      if(resources.size()>0) {
2777        sb.append(", ");
2778      }
2779    }
2780    toString(resources, sb);
2781    return sb.toString();
2782  }
2783  
2784  private <T> void toString(List<T> resources, StringBuilder sb) {
2785    ListIterator<T> i = resources.listIterator();
2786    while (i.hasNext()) {
2787      if (i.nextIndex() != 0) {
2788        sb.append(", ");
2789      }
2790      sb.append(i.next());
2791    }
2792  }
2793
2794  /** 
2795   * Set the quietness-mode. 
2796   * 
2797   * In the quiet-mode, error and informational messages might not be logged.
2798   * 
2799   * @param quietmode <code>true</code> to set quiet-mode on, <code>false</code>
2800   *              to turn it off.
2801   */
2802  public synchronized void setQuietMode(boolean quietmode) {
2803    this.quietmode = quietmode;
2804  }
2805
2806  synchronized boolean getQuietMode() {
2807    return this.quietmode;
2808  }
2809  
2810  /** For debugging.  List non-default properties to the terminal and exit. */
2811  public static void main(String[] args) throws Exception {
2812    new Configuration().writeXml(System.out);
2813  }
2814
2815  @Override
2816  public void readFields(DataInput in) throws IOException {
2817    clear();
2818    int size = WritableUtils.readVInt(in);
2819    for(int i=0; i < size; ++i) {
2820      String key = org.apache.hadoop.io.Text.readString(in);
2821      String value = org.apache.hadoop.io.Text.readString(in);
2822      set(key, value); 
2823      String sources[] = WritableUtils.readCompressedStringArray(in);
2824      updatingResource.put(key, sources);
2825    }
2826  }
2827
2828  //@Override
2829  @Override
2830  public void write(DataOutput out) throws IOException {
2831    Properties props = getProps();
2832    WritableUtils.writeVInt(out, props.size());
2833    for(Map.Entry<Object, Object> item: props.entrySet()) {
2834      org.apache.hadoop.io.Text.writeString(out, (String) item.getKey());
2835      org.apache.hadoop.io.Text.writeString(out, (String) item.getValue());
2836      WritableUtils.writeCompressedStringArray(out, 
2837          updatingResource.get(item.getKey()));
2838    }
2839  }
2840  
2841  /**
2842   * get keys matching the the regex 
2843   * @param regex
2844   * @return Map<String,String> with matching keys
2845   */
2846  public Map<String,String> getValByRegex(String regex) {
2847    Pattern p = Pattern.compile(regex);
2848
2849    Map<String,String> result = new HashMap<String,String>();
2850    Matcher m;
2851
2852    for(Map.Entry<Object,Object> item: getProps().entrySet()) {
2853      if (item.getKey() instanceof String && 
2854          item.getValue() instanceof String) {
2855        m = p.matcher((String)item.getKey());
2856        if(m.find()) { // match
2857          result.put((String) item.getKey(),
2858              substituteVars(getProps().getProperty((String) item.getKey())));
2859        }
2860      }
2861    }
2862    return result;
2863  }
2864
2865  /**
2866   * A unique class which is used as a sentinel value in the caching
2867   * for getClassByName. {@see Configuration#getClassByNameOrNull(String)}
2868   */
2869  private static abstract class NegativeCacheSentinel {}
2870
2871  public static void dumpDeprecatedKeys() {
2872    DeprecationContext deprecations = deprecationContext.get();
2873    for (Map.Entry<String, DeprecatedKeyInfo> entry :
2874        deprecations.getDeprecatedKeyMap().entrySet()) {
2875      StringBuilder newKeys = new StringBuilder();
2876      for (String newKey : entry.getValue().newKeys) {
2877        newKeys.append(newKey).append("\t");
2878      }
2879      System.out.println(entry.getKey() + "\t" + newKeys.toString());
2880    }
2881  }
2882
2883  /**
2884   * Returns whether or not a deprecated name has been warned. If the name is not
2885   * deprecated then always return false
2886   */
2887  public static boolean hasWarnedDeprecation(String name) {
2888    DeprecationContext deprecations = deprecationContext.get();
2889    if(deprecations.getDeprecatedKeyMap().containsKey(name)) {
2890      if(deprecations.getDeprecatedKeyMap().get(name).accessed.get()) {
2891        return true;
2892      }
2893    }
2894    return false;
2895  }
2896}