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