text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

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