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