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