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    
019    package org.apache.hadoop.conf;
020    
021    import java.io.BufferedInputStream;
022    import java.io.DataInput;
023    import java.io.DataOutput;
024    import java.io.File;
025    import java.io.FileInputStream;
026    import java.io.IOException;
027    import java.io.InputStream;
028    import java.io.InputStreamReader;
029    import java.io.OutputStream;
030    import java.io.OutputStreamWriter;
031    import java.io.Reader;
032    import java.io.Writer;
033    import java.lang.ref.WeakReference;
034    import java.net.InetSocketAddress;
035    import java.net.URL;
036    import java.util.ArrayList;
037    import java.util.Arrays;
038    import java.util.Collection;
039    import java.util.Collections;
040    import java.util.Enumeration;
041    import java.util.HashMap;
042    import java.util.HashSet;
043    import java.util.Iterator;
044    import java.util.LinkedList;
045    import java.util.List;
046    import java.util.ListIterator;
047    import java.util.Map;
048    import java.util.Map.Entry;
049    import java.util.Properties;
050    import java.util.Set;
051    import java.util.StringTokenizer;
052    import java.util.WeakHashMap;
053    import java.util.concurrent.CopyOnWriteArrayList;
054    import java.util.regex.Matcher;
055    import java.util.regex.Pattern;
056    import java.util.regex.PatternSyntaxException;
057    import java.util.concurrent.TimeUnit;
058    import java.util.concurrent.atomic.AtomicBoolean;
059    import java.util.concurrent.atomic.AtomicReference;
060    
061    import javax.xml.parsers.DocumentBuilder;
062    import javax.xml.parsers.DocumentBuilderFactory;
063    import javax.xml.parsers.ParserConfigurationException;
064    import javax.xml.transform.Transformer;
065    import javax.xml.transform.TransformerException;
066    import javax.xml.transform.TransformerFactory;
067    import javax.xml.transform.dom.DOMSource;
068    import javax.xml.transform.stream.StreamResult;
069    
070    import org.apache.commons.collections.map.UnmodifiableMap;
071    import org.apache.commons.logging.Log;
072    import org.apache.commons.logging.LogFactory;
073    import org.apache.hadoop.classification.InterfaceAudience;
074    import org.apache.hadoop.classification.InterfaceStability;
075    import org.apache.hadoop.fs.FileSystem;
076    import org.apache.hadoop.fs.Path;
077    import org.apache.hadoop.fs.CommonConfigurationKeys;
078    import org.apache.hadoop.io.Writable;
079    import org.apache.hadoop.io.WritableUtils;
080    import org.apache.hadoop.net.NetUtils;
081    import org.apache.hadoop.util.ReflectionUtils;
082    import org.apache.hadoop.util.StringInterner;
083    import org.apache.hadoop.util.StringUtils;
084    import org.codehaus.jackson.JsonFactory;
085    import org.codehaus.jackson.JsonGenerator;
086    import org.w3c.dom.DOMException;
087    import org.w3c.dom.Document;
088    import org.w3c.dom.Element;
089    import org.w3c.dom.Node;
090    import org.w3c.dom.NodeList;
091    import org.w3c.dom.Text;
092    import org.xml.sax.SAXException;
093    
094    import 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
167    public 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("core-site.xml");
619      }
620      
621      private Properties properties;
622      private Properties overlay;
623      private ClassLoader classLoader;
624      {
625        classLoader = Thread.currentThread().getContextClassLoader();
626        if (classLoader == null) {
627          classLoader = Configuration.class.getClassLoader();
628        }
629      }
630      
631      /** A new configuration. */
632      public Configuration() {
633        this(true);
634      }
635    
636      /** A new configuration where the behavior of reading from the default 
637       * resources can be turned off.
638       * 
639       * If the parameter {@code loadDefaults} is false, the new instance
640       * will not load resources from the default files. 
641       * @param loadDefaults specifies whether to load from the default files
642       */
643      public Configuration(boolean loadDefaults) {
644        this.loadDefaults = loadDefaults;
645        updatingResource = new HashMap<String, String[]>();
646        synchronized(Configuration.class) {
647          REGISTRY.put(this, null);
648        }
649      }
650      
651      /** 
652       * A new configuration with the same settings cloned from another.
653       * 
654       * @param other the configuration from which to clone settings.
655       */
656      @SuppressWarnings("unchecked")
657      public Configuration(Configuration other) {
658       this.resources = (ArrayList<Resource>) other.resources.clone();
659       synchronized(other) {
660         if (other.properties != null) {
661           this.properties = (Properties)other.properties.clone();
662         }
663    
664         if (other.overlay!=null) {
665           this.overlay = (Properties)other.overlay.clone();
666         }
667    
668         this.updatingResource = new HashMap<String, String[]>(other.updatingResource);
669         this.finalParameters = new HashSet<String>(other.finalParameters);
670       }
671       
672        synchronized(Configuration.class) {
673          REGISTRY.put(this, null);
674        }
675        this.classLoader = other.classLoader;
676        this.loadDefaults = other.loadDefaults;
677        setQuietMode(other.getQuietMode());
678      }
679      
680      /**
681       * Add a default resource. Resources are loaded in the order of the resources 
682       * added.
683       * @param name file name. File should be present in the classpath.
684       */
685      public static synchronized void addDefaultResource(String name) {
686        if(!defaultResources.contains(name)) {
687          defaultResources.add(name);
688          for(Configuration conf : REGISTRY.keySet()) {
689            if(conf.loadDefaults) {
690              conf.reloadConfiguration();
691            }
692          }
693        }
694      }
695    
696      /**
697       * Add a configuration resource. 
698       * 
699       * The properties of this resource will override properties of previously 
700       * added resources, unless they were marked <a href="#Final">final</a>. 
701       * 
702       * @param name resource to be added, the classpath is examined for a file 
703       *             with that name.
704       */
705      public void addResource(String name) {
706        addResourceObject(new Resource(name));
707      }
708    
709      /**
710       * Add a configuration resource. 
711       * 
712       * The properties of this resource will override properties of previously 
713       * added resources, unless they were marked <a href="#Final">final</a>. 
714       * 
715       * @param url url of the resource to be added, the local filesystem is 
716       *            examined directly to find the resource, without referring to 
717       *            the classpath.
718       */
719      public void addResource(URL url) {
720        addResourceObject(new Resource(url));
721      }
722    
723      /**
724       * Add a configuration resource. 
725       * 
726       * The properties of this resource will override properties of previously 
727       * added resources, unless they were marked <a href="#Final">final</a>. 
728       * 
729       * @param file file-path of resource to be added, the local filesystem is
730       *             examined directly to find the resource, without referring to 
731       *             the classpath.
732       */
733      public void addResource(Path file) {
734        addResourceObject(new Resource(file));
735      }
736    
737      /**
738       * Add a configuration resource. 
739       * 
740       * The properties of this resource will override properties of previously 
741       * added resources, unless they were marked <a href="#Final">final</a>. 
742       * 
743       * WARNING: The contents of the InputStream will be cached, by this method. 
744       * So use this sparingly because it does increase the memory consumption.
745       * 
746       * @param in InputStream to deserialize the object from. In will be read from
747       * when a get or set is called next.  After it is read the stream will be
748       * closed. 
749       */
750      public void addResource(InputStream in) {
751        addResourceObject(new Resource(in));
752      }
753    
754      /**
755       * Add a configuration resource. 
756       * 
757       * The properties of this resource will override properties of previously 
758       * added resources, unless they were marked <a href="#Final">final</a>. 
759       * 
760       * @param in InputStream to deserialize the object from.
761       * @param name the name of the resource because InputStream.toString is not
762       * very descriptive some times.  
763       */
764      public void addResource(InputStream in, String name) {
765        addResourceObject(new Resource(in, name));
766      }
767      
768      /**
769       * Add a configuration resource.
770       *
771       * The properties of this resource will override properties of previously
772       * added resources, unless they were marked <a href="#Final">final</a>.
773       *
774       * @param conf Configuration object from which to load properties
775       */
776      public void addResource(Configuration conf) {
777        addResourceObject(new Resource(conf.getProps()));
778      }
779    
780      
781      
782      /**
783       * Reload configuration from previously added resources.
784       *
785       * This method will clear all the configuration read from the added 
786       * resources, and final parameters. This will make the resources to 
787       * be read again before accessing the values. Values that are added
788       * via set methods will overlay values read from the resources.
789       */
790      public synchronized void reloadConfiguration() {
791        properties = null;                            // trigger reload
792        finalParameters.clear();                      // clear site-limits
793      }
794      
795      private synchronized void addResourceObject(Resource resource) {
796        resources.add(resource);                      // add to resources
797        reloadConfiguration();
798      }
799      
800      private static Pattern varPat = Pattern.compile("\\$\\{[^\\}\\$\u0020]+\\}");
801      private static int MAX_SUBST = 20;
802    
803      private String substituteVars(String expr) {
804        if (expr == null) {
805          return null;
806        }
807        Matcher match = varPat.matcher("");
808        String eval = expr;
809        for(int s=0; s<MAX_SUBST; s++) {
810          match.reset(eval);
811          if (!match.find()) {
812            return eval;
813          }
814          String var = match.group();
815          var = var.substring(2, var.length()-1); // remove ${ .. }
816          String val = null;
817          try {
818            val = System.getProperty(var);
819          } catch(SecurityException se) {
820            LOG.warn("Unexpected SecurityException in Configuration", se);
821          }
822          if (val == null) {
823            val = getRaw(var);
824          }
825          if (val == null) {
826            return eval; // return literal ${var}: var is unbound
827          }
828          // substitute
829          eval = eval.substring(0, match.start())+val+eval.substring(match.end());
830        }
831        throw new IllegalStateException("Variable substitution depth too large: " 
832                                        + MAX_SUBST + " " + expr);
833      }
834      
835      /**
836       * Get the value of the <code>name</code> property, <code>null</code> if
837       * no such property exists. If the key is deprecated, it returns the value of
838       * the first key which replaces the deprecated key and is not null
839       * 
840       * Values are processed for <a href="#VariableExpansion">variable expansion</a> 
841       * before being returned. 
842       * 
843       * @param name the property name.
844       * @return the value of the <code>name</code> or its replacing property, 
845       *         or null if no such property exists.
846       */
847      public String get(String name) {
848        String[] names = handleDeprecation(deprecationContext.get(), name);
849        String result = null;
850        for(String n : names) {
851          result = substituteVars(getProps().getProperty(n));
852        }
853        return result;
854      }
855      
856      /**
857       * Get the value of the <code>name</code> property as a trimmed <code>String</code>, 
858       * <code>null</code> if no such property exists. 
859       * If the key is deprecated, it returns the value of
860       * the first key which replaces the deprecated key and is not null
861       * 
862       * Values are processed for <a href="#VariableExpansion">variable expansion</a> 
863       * before being returned. 
864       * 
865       * @param name the property name.
866       * @return the value of the <code>name</code> or its replacing property, 
867       *         or null if no such property exists.
868       */
869      public String getTrimmed(String name) {
870        String value = get(name);
871        
872        if (null == value) {
873          return null;
874        } else {
875          return value.trim();
876        }
877      }
878      
879      /**
880       * Get the value of the <code>name</code> property as a trimmed <code>String</code>, 
881       * <code>defaultValue</code> if no such property exists. 
882       * See @{Configuration#getTrimmed} for more details.
883       * 
884       * @param name          the property name.
885       * @param defaultValue  the property default value.
886       * @return              the value of the <code>name</code> or defaultValue
887       *                      if it is not set.
888       */
889      public String getTrimmed(String name, String defaultValue) {
890        String ret = getTrimmed(name);
891        return ret == null ? defaultValue : ret;
892      }
893    
894      /**
895       * Get the value of the <code>name</code> property, without doing
896       * <a href="#VariableExpansion">variable expansion</a>.If the key is 
897       * deprecated, it returns the value of the first key which replaces 
898       * the deprecated key and is not null.
899       * 
900       * @param name the property name.
901       * @return the value of the <code>name</code> property or 
902       *         its replacing property and null if no such property exists.
903       */
904      public String getRaw(String name) {
905        String[] names = handleDeprecation(deprecationContext.get(), name);
906        String result = null;
907        for(String n : names) {
908          result = getProps().getProperty(n);
909        }
910        return result;
911      }
912    
913      /**
914       * Returns alternative names (non-deprecated keys or previously-set deprecated keys)
915       * for a given non-deprecated key.
916       * If the given key is deprecated, return null.
917       *
918       * @param name property name.
919       * @return alternative names.
920       */
921      private String[] getAlternativeNames(String name) {
922        String altNames[] = null;
923        DeprecatedKeyInfo keyInfo = null;
924        DeprecationContext cur = deprecationContext.get();
925        String depKey = cur.getReverseDeprecatedKeyMap().get(name);
926        if(depKey != null) {
927          keyInfo = cur.getDeprecatedKeyMap().get(depKey);
928          if(keyInfo.newKeys.length > 0) {
929            if(getProps().containsKey(depKey)) {
930              //if deprecated key is previously set explicitly
931              List<String> list = new ArrayList<String>();
932              list.addAll(Arrays.asList(keyInfo.newKeys));
933              list.add(depKey);
934              altNames = list.toArray(new String[list.size()]);
935            }
936            else {
937              altNames = keyInfo.newKeys;
938            }
939          }
940        }
941        return altNames;
942      }
943    
944      /** 
945       * Set the <code>value</code> of the <code>name</code> property. If 
946       * <code>name</code> is deprecated or there is a deprecated name associated to it,
947       * it sets the value to both names.
948       * 
949       * @param name property name.
950       * @param value property value.
951       */
952      public void set(String name, String value) {
953        set(name, value, null);
954      }
955      
956      /** 
957       * Set the <code>value</code> of the <code>name</code> property. If 
958       * <code>name</code> is deprecated, it also sets the <code>value</code> to
959       * the keys that replace the deprecated key.
960       *
961       * @param name property name.
962       * @param value property value.
963       * @param source the place that this configuration value came from 
964       * (For debugging).
965       * @throws IllegalArgumentException when the value or name is null.
966       */
967      public void set(String name, String value, String source) {
968        Preconditions.checkArgument(
969            name != null,
970            "Property name must not be null");
971        Preconditions.checkArgument(
972            value != null,
973            "The value of property " + name + " must not be null");
974        DeprecationContext deprecations = deprecationContext.get();
975        if (deprecations.getDeprecatedKeyMap().isEmpty()) {
976          getProps();
977        }
978        getOverlay().setProperty(name, value);
979        getProps().setProperty(name, value);
980        String newSource = (source == null ? "programatically" : source);
981    
982        if (!isDeprecated(name)) {
983          updatingResource.put(name, new String[] {newSource});
984          String[] altNames = getAlternativeNames(name);
985          if(altNames != null) {
986            for(String n: altNames) {
987              if(!n.equals(name)) {
988                getOverlay().setProperty(n, value);
989                getProps().setProperty(n, value);
990                updatingResource.put(n, new String[] {newSource});
991              }
992            }
993          }
994        }
995        else {
996          String[] names = handleDeprecation(deprecationContext.get(), name);
997          String altSource = "because " + name + " is deprecated";
998          for(String n : names) {
999            getOverlay().setProperty(n, value);
1000            getProps().setProperty(n, value);
1001            updatingResource.put(n, new String[] {altSource});
1002          }
1003        }
1004      }
1005    
1006      private void warnOnceIfDeprecated(DeprecationContext deprecations, String name) {
1007        DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(name);
1008        if (keyInfo != null && !keyInfo.getAndSetAccessed()) {
1009          LOG_DEPRECATION.info(keyInfo.getWarningMessage(name));
1010        }
1011      }
1012    
1013      /**
1014       * Unset a previously set property.
1015       */
1016      public synchronized void unset(String name) {
1017        String[] names = null;
1018        if (!isDeprecated(name)) {
1019          names = getAlternativeNames(name);
1020          if(names == null) {
1021              names = new String[]{name};
1022          }
1023        }
1024        else {
1025          names = handleDeprecation(deprecationContext.get(), name);
1026        }
1027    
1028        for(String n: names) {
1029          getOverlay().remove(n);
1030          getProps().remove(n);
1031        }
1032      }
1033    
1034      /**
1035       * Sets a property if it is currently unset.
1036       * @param name the property name
1037       * @param value the new value
1038       */
1039      public synchronized void setIfUnset(String name, String value) {
1040        if (get(name) == null) {
1041          set(name, value);
1042        }
1043      }
1044      
1045      private synchronized Properties getOverlay() {
1046        if (overlay==null){
1047          overlay=new Properties();
1048        }
1049        return overlay;
1050      }
1051    
1052      /** 
1053       * Get the value of the <code>name</code>. If the key is deprecated,
1054       * it returns the value of the first key which replaces the deprecated key
1055       * and is not null.
1056       * If no such property exists,
1057       * then <code>defaultValue</code> is returned.
1058       * 
1059       * @param name property name.
1060       * @param defaultValue default value.
1061       * @return property value, or <code>defaultValue</code> if the property 
1062       *         doesn't exist.                    
1063       */
1064      public String get(String name, String defaultValue) {
1065        String[] names = handleDeprecation(deprecationContext.get(), name);
1066        String result = null;
1067        for(String n : names) {
1068          result = substituteVars(getProps().getProperty(n, defaultValue));
1069        }
1070        return result;
1071      }
1072    
1073      /** 
1074       * Get the value of the <code>name</code> property as an <code>int</code>.
1075       *   
1076       * If no such property exists, the provided default value is returned,
1077       * or if the specified value is not a valid <code>int</code>,
1078       * then an error is thrown.
1079       * 
1080       * @param name property name.
1081       * @param defaultValue default value.
1082       * @throws NumberFormatException when the value is invalid
1083       * @return property value as an <code>int</code>, 
1084       *         or <code>defaultValue</code>. 
1085       */
1086      public int getInt(String name, int defaultValue) {
1087        String valueString = getTrimmed(name);
1088        if (valueString == null)
1089          return defaultValue;
1090        String hexString = getHexDigits(valueString);
1091        if (hexString != null) {
1092          return Integer.parseInt(hexString, 16);
1093        }
1094        return Integer.parseInt(valueString);
1095      }
1096      
1097      /**
1098       * Get the value of the <code>name</code> property as a set of comma-delimited
1099       * <code>int</code> values.
1100       * 
1101       * If no such property exists, an empty array is returned.
1102       * 
1103       * @param name property name
1104       * @return property value interpreted as an array of comma-delimited
1105       *         <code>int</code> values
1106       */
1107      public int[] getInts(String name) {
1108        String[] strings = getTrimmedStrings(name);
1109        int[] ints = new int[strings.length];
1110        for (int i = 0; i < strings.length; i++) {
1111          ints[i] = Integer.parseInt(strings[i]);
1112        }
1113        return ints;
1114      }
1115    
1116      /** 
1117       * Set the value of the <code>name</code> property to an <code>int</code>.
1118       * 
1119       * @param name property name.
1120       * @param value <code>int</code> value of the property.
1121       */
1122      public void setInt(String name, int value) {
1123        set(name, Integer.toString(value));
1124      }
1125    
1126    
1127      /** 
1128       * Get the value of the <code>name</code> property as a <code>long</code>.  
1129       * If no such property exists, the provided default value is returned,
1130       * or if the specified value is not a valid <code>long</code>,
1131       * then an error is thrown.
1132       * 
1133       * @param name property name.
1134       * @param defaultValue default value.
1135       * @throws NumberFormatException when the value is invalid
1136       * @return property value as a <code>long</code>, 
1137       *         or <code>defaultValue</code>. 
1138       */
1139      public long getLong(String name, long defaultValue) {
1140        String valueString = getTrimmed(name);
1141        if (valueString == null)
1142          return defaultValue;
1143        String hexString = getHexDigits(valueString);
1144        if (hexString != null) {
1145          return Long.parseLong(hexString, 16);
1146        }
1147        return Long.parseLong(valueString);
1148      }
1149    
1150      /**
1151       * Get the value of the <code>name</code> property as a <code>long</code> or
1152       * human readable format. If no such property exists, the provided default
1153       * value is returned, or if the specified value is not a valid
1154       * <code>long</code> or human readable format, then an error is thrown. You
1155       * can use the following suffix (case insensitive): k(kilo), m(mega), g(giga),
1156       * t(tera), p(peta), e(exa)
1157       *
1158       * @param name property name.
1159       * @param defaultValue default value.
1160       * @throws NumberFormatException when the value is invalid
1161       * @return property value as a <code>long</code>,
1162       *         or <code>defaultValue</code>.
1163       */
1164      public long getLongBytes(String name, long defaultValue) {
1165        String valueString = getTrimmed(name);
1166        if (valueString == null)
1167          return defaultValue;
1168        return StringUtils.TraditionalBinaryPrefix.string2long(valueString);
1169      }
1170    
1171      private String getHexDigits(String value) {
1172        boolean negative = false;
1173        String str = value;
1174        String hexString = null;
1175        if (value.startsWith("-")) {
1176          negative = true;
1177          str = value.substring(1);
1178        }
1179        if (str.startsWith("0x") || str.startsWith("0X")) {
1180          hexString = str.substring(2);
1181          if (negative) {
1182            hexString = "-" + hexString;
1183          }
1184          return hexString;
1185        }
1186        return null;
1187      }
1188      
1189      /** 
1190       * Set the value of the <code>name</code> property to a <code>long</code>.
1191       * 
1192       * @param name property name.
1193       * @param value <code>long</code> value of the property.
1194       */
1195      public void setLong(String name, long value) {
1196        set(name, Long.toString(value));
1197      }
1198    
1199      /** 
1200       * Get the value of the <code>name</code> property as a <code>float</code>.  
1201       * If no such property exists, the provided default value is returned,
1202       * or if the specified value is not a valid <code>float</code>,
1203       * then an error is thrown.
1204       *
1205       * @param name property name.
1206       * @param defaultValue default value.
1207       * @throws NumberFormatException when the value is invalid
1208       * @return property value as a <code>float</code>, 
1209       *         or <code>defaultValue</code>. 
1210       */
1211      public float getFloat(String name, float defaultValue) {
1212        String valueString = getTrimmed(name);
1213        if (valueString == null)
1214          return defaultValue;
1215        return Float.parseFloat(valueString);
1216      }
1217    
1218      /**
1219       * Set the value of the <code>name</code> property to a <code>float</code>.
1220       * 
1221       * @param name property name.
1222       * @param value property value.
1223       */
1224      public void setFloat(String name, float value) {
1225        set(name,Float.toString(value));
1226      }
1227    
1228      /** 
1229       * Get the value of the <code>name</code> property as a <code>double</code>.  
1230       * If no such property exists, the provided default value is returned,
1231       * or if the specified value is not a valid <code>double</code>,
1232       * then an error is thrown.
1233       *
1234       * @param name property name.
1235       * @param defaultValue default value.
1236       * @throws NumberFormatException when the value is invalid
1237       * @return property value as a <code>double</code>, 
1238       *         or <code>defaultValue</code>. 
1239       */
1240      public double getDouble(String name, double defaultValue) {
1241        String valueString = getTrimmed(name);
1242        if (valueString == null)
1243          return defaultValue;
1244        return Double.parseDouble(valueString);
1245      }
1246    
1247      /**
1248       * Set the value of the <code>name</code> property to a <code>double</code>.
1249       * 
1250       * @param name property name.
1251       * @param value property value.
1252       */
1253      public void setDouble(String name, double value) {
1254        set(name,Double.toString(value));
1255      }
1256     
1257      /** 
1258       * Get the value of the <code>name</code> property as a <code>boolean</code>.  
1259       * If no such property is specified, or if the specified value is not a valid
1260       * <code>boolean</code>, then <code>defaultValue</code> is returned.
1261       * 
1262       * @param name property name.
1263       * @param defaultValue default value.
1264       * @return property value as a <code>boolean</code>, 
1265       *         or <code>defaultValue</code>. 
1266       */
1267      public boolean getBoolean(String name, boolean defaultValue) {
1268        String valueString = getTrimmed(name);
1269        if (null == valueString || valueString.isEmpty()) {
1270          return defaultValue;
1271        }
1272    
1273        valueString = valueString.toLowerCase();
1274    
1275        if ("true".equals(valueString))
1276          return true;
1277        else if ("false".equals(valueString))
1278          return false;
1279        else return defaultValue;
1280      }
1281    
1282      /** 
1283       * Set the value of the <code>name</code> property to a <code>boolean</code>.
1284       * 
1285       * @param name property name.
1286       * @param value <code>boolean</code> value of the property.
1287       */
1288      public void setBoolean(String name, boolean value) {
1289        set(name, Boolean.toString(value));
1290      }
1291    
1292      /**
1293       * Set the given property, if it is currently unset.
1294       * @param name property name
1295       * @param value new value
1296       */
1297      public void setBooleanIfUnset(String name, boolean value) {
1298        setIfUnset(name, Boolean.toString(value));
1299      }
1300    
1301      /**
1302       * Set the value of the <code>name</code> property to the given type. This
1303       * is equivalent to <code>set(&lt;name&gt;, value.toString())</code>.
1304       * @param name property name
1305       * @param value new value
1306       */
1307      public <T extends Enum<T>> void setEnum(String name, T value) {
1308        set(name, value.toString());
1309      }
1310    
1311      /**
1312       * Return value matching this enumerated type.
1313       * @param name Property name
1314       * @param defaultValue Value returned if no mapping exists
1315       * @throws IllegalArgumentException If mapping is illegal for the type
1316       * provided
1317       */
1318      public <T extends Enum<T>> T getEnum(String name, T defaultValue) {
1319        final String val = get(name);
1320        return null == val
1321          ? defaultValue
1322          : Enum.valueOf(defaultValue.getDeclaringClass(), val);
1323      }
1324    
1325      enum ParsedTimeDuration {
1326        NS {
1327          TimeUnit unit() { return TimeUnit.NANOSECONDS; }
1328          String suffix() { return "ns"; }
1329        },
1330        US {
1331          TimeUnit unit() { return TimeUnit.MICROSECONDS; }
1332          String suffix() { return "us"; }
1333        },
1334        MS {
1335          TimeUnit unit() { return TimeUnit.MILLISECONDS; }
1336          String suffix() { return "ms"; }
1337        },
1338        S {
1339          TimeUnit unit() { return TimeUnit.SECONDS; }
1340          String suffix() { return "s"; }
1341        },
1342        M {
1343          TimeUnit unit() { return TimeUnit.MINUTES; }
1344          String suffix() { return "m"; }
1345        },
1346        H {
1347          TimeUnit unit() { return TimeUnit.HOURS; }
1348          String suffix() { return "h"; }
1349        },
1350        D {
1351          TimeUnit unit() { return TimeUnit.DAYS; }
1352          String suffix() { return "d"; }
1353        };
1354        abstract TimeUnit unit();
1355        abstract String suffix();
1356        static ParsedTimeDuration unitFor(String s) {
1357          for (ParsedTimeDuration ptd : values()) {
1358            // iteration order is in decl order, so SECONDS matched last
1359            if (s.endsWith(ptd.suffix())) {
1360              return ptd;
1361            }
1362          }
1363          return null;
1364        }
1365        static ParsedTimeDuration unitFor(TimeUnit unit) {
1366          for (ParsedTimeDuration ptd : values()) {
1367            if (ptd.unit() == unit) {
1368              return ptd;
1369            }
1370          }
1371          return null;
1372        }
1373      }
1374    
1375      /**
1376       * Set the value of <code>name</code> to the given time duration. This
1377       * is equivalent to <code>set(&lt;name&gt;, value + &lt;time suffix&gt;)</code>.
1378       * @param name Property name
1379       * @param value Time duration
1380       * @param unit Unit of time
1381       */
1382      public void setTimeDuration(String name, long value, TimeUnit unit) {
1383        set(name, value + ParsedTimeDuration.unitFor(unit).suffix());
1384      }
1385    
1386      /**
1387       * Return time duration in the given time unit. Valid units are encoded in
1388       * properties as suffixes: nanoseconds (ns), microseconds (us), milliseconds
1389       * (ms), seconds (s), minutes (m), hours (h), and days (d).
1390       * @param name Property name
1391       * @param defaultValue Value returned if no mapping exists.
1392       * @param unit Unit to convert the stored property, if it exists.
1393       * @throws NumberFormatException If the property stripped of its unit is not
1394       *         a number
1395       */
1396      public long getTimeDuration(String name, long defaultValue, TimeUnit unit) {
1397        String vStr = get(name);
1398        if (null == vStr) {
1399          return defaultValue;
1400        }
1401        vStr = vStr.trim();
1402        ParsedTimeDuration vUnit = ParsedTimeDuration.unitFor(vStr);
1403        if (null == vUnit) {
1404          LOG.warn("No unit for " + name + "(" + vStr + ") assuming " + unit);
1405          vUnit = ParsedTimeDuration.unitFor(unit);
1406        } else {
1407          vStr = vStr.substring(0, vStr.lastIndexOf(vUnit.suffix()));
1408        }
1409        return unit.convert(Long.parseLong(vStr), vUnit.unit());
1410      }
1411    
1412      /**
1413       * Get the value of the <code>name</code> property as a <code>Pattern</code>.
1414       * If no such property is specified, or if the specified value is not a valid
1415       * <code>Pattern</code>, then <code>DefaultValue</code> is returned.
1416       *
1417       * @param name property name
1418       * @param defaultValue default value
1419       * @return property value as a compiled Pattern, or defaultValue
1420       */
1421      public Pattern getPattern(String name, Pattern defaultValue) {
1422        String valString = get(name);
1423        if (null == valString || valString.isEmpty()) {
1424          return defaultValue;
1425        }
1426        try {
1427          return Pattern.compile(valString);
1428        } catch (PatternSyntaxException pse) {
1429          LOG.warn("Regular expression '" + valString + "' for property '" +
1430                   name + "' not valid. Using default", pse);
1431          return defaultValue;
1432        }
1433      }
1434    
1435      /**
1436       * Set the given property to <code>Pattern</code>.
1437       * If the pattern is passed as null, sets the empty pattern which results in
1438       * further calls to getPattern(...) returning the default value.
1439       *
1440       * @param name property name
1441       * @param pattern new value
1442       */
1443      public void setPattern(String name, Pattern pattern) {
1444        if (null == pattern) {
1445          set(name, null);
1446        } else {
1447          set(name, pattern.pattern());
1448        }
1449      }
1450    
1451      /**
1452       * Gets information about why a property was set.  Typically this is the 
1453       * path to the resource objects (file, URL, etc.) the property came from, but
1454       * it can also indicate that it was set programatically, or because of the
1455       * command line.
1456       *
1457       * @param name - The property name to get the source of.
1458       * @return null - If the property or its source wasn't found. Otherwise, 
1459       * returns a list of the sources of the resource.  The older sources are
1460       * the first ones in the list.  So for example if a configuration is set from
1461       * the command line, and then written out to a file that is read back in the
1462       * first entry would indicate that it was set from the command line, while
1463       * the second one would indicate the file that the new configuration was read
1464       * in from.
1465       */
1466      @InterfaceStability.Unstable
1467      public synchronized String[] getPropertySources(String name) {
1468        if (properties == null) {
1469          // If properties is null, it means a resource was newly added
1470          // but the props were cleared so as to load it upon future
1471          // requests. So lets force a load by asking a properties list.
1472          getProps();
1473        }
1474        // Return a null right away if our properties still
1475        // haven't loaded or the resource mapping isn't defined
1476        if (properties == null || updatingResource == null) {
1477          return null;
1478        } else {
1479          String[] source = updatingResource.get(name);
1480          if(source == null) {
1481            return null;
1482          } else {
1483            return Arrays.copyOf(source, source.length);
1484          }
1485        }
1486      }
1487    
1488      /**
1489       * A class that represents a set of positive integer ranges. It parses 
1490       * strings of the form: "2-3,5,7-" where ranges are separated by comma and 
1491       * the lower/upper bounds are separated by dash. Either the lower or upper 
1492       * bound may be omitted meaning all values up to or over. So the string 
1493       * above means 2, 3, 5, and 7, 8, 9, ...
1494       */
1495      public static class IntegerRanges implements Iterable<Integer>{
1496        private static class Range {
1497          int start;
1498          int end;
1499        }
1500        
1501        private static class RangeNumberIterator implements Iterator<Integer> {
1502          Iterator<Range> internal;
1503          int at;
1504          int end;
1505    
1506          public RangeNumberIterator(List<Range> ranges) {
1507            if (ranges != null) {
1508              internal = ranges.iterator();
1509            }
1510            at = -1;
1511            end = -2;
1512          }
1513          
1514          @Override
1515          public boolean hasNext() {
1516            if (at <= end) {
1517              return true;
1518            } else if (internal != null){
1519              return internal.hasNext();
1520            }
1521            return false;
1522          }
1523    
1524          @Override
1525          public Integer next() {
1526            if (at <= end) {
1527              at++;
1528              return at - 1;
1529            } else if (internal != null){
1530              Range found = internal.next();
1531              if (found != null) {
1532                at = found.start;
1533                end = found.end;
1534                at++;
1535                return at - 1;
1536              }
1537            }
1538            return null;
1539          }
1540    
1541          @Override
1542          public void remove() {
1543            throw new UnsupportedOperationException();
1544          }
1545        };
1546    
1547        List<Range> ranges = new ArrayList<Range>();
1548        
1549        public IntegerRanges() {
1550        }
1551        
1552        public IntegerRanges(String newValue) {
1553          StringTokenizer itr = new StringTokenizer(newValue, ",");
1554          while (itr.hasMoreTokens()) {
1555            String rng = itr.nextToken().trim();
1556            String[] parts = rng.split("-", 3);
1557            if (parts.length < 1 || parts.length > 2) {
1558              throw new IllegalArgumentException("integer range badly formed: " + 
1559                                                 rng);
1560            }
1561            Range r = new Range();
1562            r.start = convertToInt(parts[0], 0);
1563            if (parts.length == 2) {
1564              r.end = convertToInt(parts[1], Integer.MAX_VALUE);
1565            } else {
1566              r.end = r.start;
1567            }
1568            if (r.start > r.end) {
1569              throw new IllegalArgumentException("IntegerRange from " + r.start + 
1570                                                 " to " + r.end + " is invalid");
1571            }
1572            ranges.add(r);
1573          }
1574        }
1575    
1576        /**
1577         * Convert a string to an int treating empty strings as the default value.
1578         * @param value the string value
1579         * @param defaultValue the value for if the string is empty
1580         * @return the desired integer
1581         */
1582        private static int convertToInt(String value, int defaultValue) {
1583          String trim = value.trim();
1584          if (trim.length() == 0) {
1585            return defaultValue;
1586          }
1587          return Integer.parseInt(trim);
1588        }
1589    
1590        /**
1591         * Is the given value in the set of ranges
1592         * @param value the value to check
1593         * @return is the value in the ranges?
1594         */
1595        public boolean isIncluded(int value) {
1596          for(Range r: ranges) {
1597            if (r.start <= value && value <= r.end) {
1598              return true;
1599            }
1600          }
1601          return false;
1602        }
1603        
1604        /**
1605         * @return true if there are no values in this range, else false.
1606         */
1607        public boolean isEmpty() {
1608          return ranges == null || ranges.isEmpty();
1609        }
1610        
1611        @Override
1612        public String toString() {
1613          StringBuilder result = new StringBuilder();
1614          boolean first = true;
1615          for(Range r: ranges) {
1616            if (first) {
1617              first = false;
1618            } else {
1619              result.append(',');
1620            }
1621            result.append(r.start);
1622            result.append('-');
1623            result.append(r.end);
1624          }
1625          return result.toString();
1626        }
1627    
1628        @Override
1629        public Iterator<Integer> iterator() {
1630          return new RangeNumberIterator(ranges);
1631        }
1632        
1633      }
1634    
1635      /**
1636       * Parse the given attribute as a set of integer ranges
1637       * @param name the attribute name
1638       * @param defaultValue the default value if it is not set
1639       * @return a new set of ranges from the configured value
1640       */
1641      public IntegerRanges getRange(String name, String defaultValue) {
1642        return new IntegerRanges(get(name, defaultValue));
1643      }
1644    
1645      /** 
1646       * Get the comma delimited values of the <code>name</code> property as 
1647       * a collection of <code>String</code>s.  
1648       * If no such property is specified then empty collection is returned.
1649       * <p>
1650       * This is an optimized version of {@link #getStrings(String)}
1651       * 
1652       * @param name property name.
1653       * @return property value as a collection of <code>String</code>s. 
1654       */
1655      public Collection<String> getStringCollection(String name) {
1656        String valueString = get(name);
1657        return StringUtils.getStringCollection(valueString);
1658      }
1659    
1660      /** 
1661       * Get the comma delimited values of the <code>name</code> property as 
1662       * an array of <code>String</code>s.  
1663       * If no such property is specified then <code>null</code> is returned.
1664       * 
1665       * @param name property name.
1666       * @return property value as an array of <code>String</code>s, 
1667       *         or <code>null</code>. 
1668       */
1669      public String[] getStrings(String name) {
1670        String valueString = get(name);
1671        return StringUtils.getStrings(valueString);
1672      }
1673    
1674      /** 
1675       * Get the comma delimited values of the <code>name</code> property as 
1676       * an array of <code>String</code>s.  
1677       * If no such property is specified then default value is returned.
1678       * 
1679       * @param name property name.
1680       * @param defaultValue The default value
1681       * @return property value as an array of <code>String</code>s, 
1682       *         or default value. 
1683       */
1684      public String[] getStrings(String name, String... defaultValue) {
1685        String valueString = get(name);
1686        if (valueString == null) {
1687          return defaultValue;
1688        } else {
1689          return StringUtils.getStrings(valueString);
1690        }
1691      }
1692      
1693      /** 
1694       * Get the comma delimited values of the <code>name</code> property as 
1695       * a collection of <code>String</code>s, trimmed of the leading and trailing whitespace.  
1696       * If no such property is specified then empty <code>Collection</code> is returned.
1697       *
1698       * @param name property name.
1699       * @return property value as a collection of <code>String</code>s, or empty <code>Collection</code> 
1700       */
1701      public Collection<String> getTrimmedStringCollection(String name) {
1702        String valueString = get(name);
1703        if (null == valueString) {
1704          Collection<String> empty = new ArrayList<String>();
1705          return empty;
1706        }
1707        return StringUtils.getTrimmedStringCollection(valueString);
1708      }
1709      
1710      /** 
1711       * Get the comma delimited values of the <code>name</code> property as 
1712       * an array of <code>String</code>s, trimmed of the leading and trailing whitespace.
1713       * If no such property is specified then an empty array is returned.
1714       * 
1715       * @param name property name.
1716       * @return property value as an array of trimmed <code>String</code>s, 
1717       *         or empty array. 
1718       */
1719      public String[] getTrimmedStrings(String name) {
1720        String valueString = get(name);
1721        return StringUtils.getTrimmedStrings(valueString);
1722      }
1723    
1724      /** 
1725       * Get the comma delimited values of the <code>name</code> property as 
1726       * an array of <code>String</code>s, trimmed of the leading and trailing whitespace.
1727       * If no such property is specified then default value is returned.
1728       * 
1729       * @param name property name.
1730       * @param defaultValue The default value
1731       * @return property value as an array of trimmed <code>String</code>s, 
1732       *         or default value. 
1733       */
1734      public String[] getTrimmedStrings(String name, String... defaultValue) {
1735        String valueString = get(name);
1736        if (null == valueString) {
1737          return defaultValue;
1738        } else {
1739          return StringUtils.getTrimmedStrings(valueString);
1740        }
1741      }
1742    
1743      /** 
1744       * Set the array of string values for the <code>name</code> property as 
1745       * as comma delimited values.  
1746       * 
1747       * @param name property name.
1748       * @param values The values
1749       */
1750      public void setStrings(String name, String... values) {
1751        set(name, StringUtils.arrayToString(values));
1752      }
1753    
1754      /**
1755       * Get the socket address for <code>name</code> property as a
1756       * <code>InetSocketAddress</code>.
1757       * @param name property name.
1758       * @param defaultAddress the default value
1759       * @param defaultPort the default port
1760       * @return InetSocketAddress
1761       */
1762      public InetSocketAddress getSocketAddr(
1763          String name, String defaultAddress, int defaultPort) {
1764        final String address = get(name, defaultAddress);
1765        return NetUtils.createSocketAddr(address, defaultPort, name);
1766      }
1767    
1768      /**
1769       * Set the socket address for the <code>name</code> property as
1770       * a <code>host:port</code>.
1771       */
1772      public void setSocketAddr(String name, InetSocketAddress addr) {
1773        set(name, NetUtils.getHostPortString(addr));
1774      }
1775      
1776      /**
1777       * Set the socket address a client can use to connect for the
1778       * <code>name</code> property as a <code>host:port</code>.  The wildcard
1779       * address is replaced with the local host's address.
1780       * @param name property name.
1781       * @param addr InetSocketAddress of a listener to store in the given property
1782       * @return InetSocketAddress for clients to connect
1783       */
1784      public InetSocketAddress updateConnectAddr(String name,
1785                                                 InetSocketAddress addr) {
1786        final InetSocketAddress connectAddr = NetUtils.getConnectAddress(addr);
1787        setSocketAddr(name, connectAddr);
1788        return connectAddr;
1789      }
1790      
1791      /**
1792       * Load a class by name.
1793       * 
1794       * @param name the class name.
1795       * @return the class object.
1796       * @throws ClassNotFoundException if the class is not found.
1797       */
1798      public Class<?> getClassByName(String name) throws ClassNotFoundException {
1799        Class<?> ret = getClassByNameOrNull(name);
1800        if (ret == null) {
1801          throw new ClassNotFoundException("Class " + name + " not found");
1802        }
1803        return ret;
1804      }
1805      
1806      /**
1807       * Load a class by name, returning null rather than throwing an exception
1808       * if it couldn't be loaded. This is to avoid the overhead of creating
1809       * an exception.
1810       * 
1811       * @param name the class name
1812       * @return the class object, or null if it could not be found.
1813       */
1814      public Class<?> getClassByNameOrNull(String name) {
1815        Map<String, WeakReference<Class<?>>> map;
1816        
1817        synchronized (CACHE_CLASSES) {
1818          map = CACHE_CLASSES.get(classLoader);
1819          if (map == null) {
1820            map = Collections.synchronizedMap(
1821              new WeakHashMap<String, WeakReference<Class<?>>>());
1822            CACHE_CLASSES.put(classLoader, map);
1823          }
1824        }
1825    
1826        Class<?> clazz = null;
1827        WeakReference<Class<?>> ref = map.get(name); 
1828        if (ref != null) {
1829           clazz = ref.get();
1830        }
1831         
1832        if (clazz == null) {
1833          try {
1834            clazz = Class.forName(name, true, classLoader);
1835          } catch (ClassNotFoundException e) {
1836            // Leave a marker that the class isn't found
1837            map.put(name, new WeakReference<Class<?>>(NEGATIVE_CACHE_SENTINEL));
1838            return null;
1839          }
1840          // two putters can race here, but they'll put the same class
1841          map.put(name, new WeakReference<Class<?>>(clazz));
1842          return clazz;
1843        } else if (clazz == NEGATIVE_CACHE_SENTINEL) {
1844          return null; // not found
1845        } else {
1846          // cache hit
1847          return clazz;
1848        }
1849      }
1850    
1851      /** 
1852       * Get the value of the <code>name</code> property
1853       * as an array of <code>Class</code>.
1854       * The value of the property specifies a list of comma separated class names.  
1855       * If no such property is specified, then <code>defaultValue</code> is 
1856       * returned.
1857       * 
1858       * @param name the property name.
1859       * @param defaultValue default value.
1860       * @return property value as a <code>Class[]</code>, 
1861       *         or <code>defaultValue</code>. 
1862       */
1863      public Class<?>[] getClasses(String name, Class<?> ... defaultValue) {
1864        String[] classnames = getTrimmedStrings(name);
1865        if (classnames == null)
1866          return defaultValue;
1867        try {
1868          Class<?>[] classes = new Class<?>[classnames.length];
1869          for(int i = 0; i < classnames.length; i++) {
1870            classes[i] = getClassByName(classnames[i]);
1871          }
1872          return classes;
1873        } catch (ClassNotFoundException e) {
1874          throw new RuntimeException(e);
1875        }
1876      }
1877    
1878      /** 
1879       * Get the value of the <code>name</code> property as a <code>Class</code>.  
1880       * If no such property is specified, then <code>defaultValue</code> is 
1881       * returned.
1882       * 
1883       * @param name the class name.
1884       * @param defaultValue default value.
1885       * @return property value as a <code>Class</code>, 
1886       *         or <code>defaultValue</code>. 
1887       */
1888      public Class<?> getClass(String name, Class<?> defaultValue) {
1889        String valueString = getTrimmed(name);
1890        if (valueString == null)
1891          return defaultValue;
1892        try {
1893          return getClassByName(valueString);
1894        } catch (ClassNotFoundException e) {
1895          throw new RuntimeException(e);
1896        }
1897      }
1898    
1899      /** 
1900       * Get the value of the <code>name</code> property as a <code>Class</code>
1901       * implementing the interface specified by <code>xface</code>.
1902       *   
1903       * If no such property is specified, then <code>defaultValue</code> is 
1904       * returned.
1905       * 
1906       * An exception is thrown if the returned class does not implement the named
1907       * interface. 
1908       * 
1909       * @param name the class name.
1910       * @param defaultValue default value.
1911       * @param xface the interface implemented by the named class.
1912       * @return property value as a <code>Class</code>, 
1913       *         or <code>defaultValue</code>.
1914       */
1915      public <U> Class<? extends U> getClass(String name, 
1916                                             Class<? extends U> defaultValue, 
1917                                             Class<U> xface) {
1918        try {
1919          Class<?> theClass = getClass(name, defaultValue);
1920          if (theClass != null && !xface.isAssignableFrom(theClass))
1921            throw new RuntimeException(theClass+" not "+xface.getName());
1922          else if (theClass != null)
1923            return theClass.asSubclass(xface);
1924          else
1925            return null;
1926        } catch (Exception e) {
1927          throw new RuntimeException(e);
1928        }
1929      }
1930    
1931      /**
1932       * Get the value of the <code>name</code> property as a <code>List</code>
1933       * of objects implementing the interface specified by <code>xface</code>.
1934       * 
1935       * An exception is thrown if any of the classes does not exist, or if it does
1936       * not implement the named interface.
1937       * 
1938       * @param name the property name.
1939       * @param xface the interface implemented by the classes named by
1940       *        <code>name</code>.
1941       * @return a <code>List</code> of objects implementing <code>xface</code>.
1942       */
1943      @SuppressWarnings("unchecked")
1944      public <U> List<U> getInstances(String name, Class<U> xface) {
1945        List<U> ret = new ArrayList<U>();
1946        Class<?>[] classes = getClasses(name);
1947        for (Class<?> cl: classes) {
1948          if (!xface.isAssignableFrom(cl)) {
1949            throw new RuntimeException(cl + " does not implement " + xface);
1950          }
1951          ret.add((U)ReflectionUtils.newInstance(cl, this));
1952        }
1953        return ret;
1954      }
1955    
1956      /** 
1957       * Set the value of the <code>name</code> property to the name of a 
1958       * <code>theClass</code> implementing the given interface <code>xface</code>.
1959       * 
1960       * An exception is thrown if <code>theClass</code> does not implement the 
1961       * interface <code>xface</code>. 
1962       * 
1963       * @param name property name.
1964       * @param theClass property value.
1965       * @param xface the interface implemented by the named class.
1966       */
1967      public void setClass(String name, Class<?> theClass, Class<?> xface) {
1968        if (!xface.isAssignableFrom(theClass))
1969          throw new RuntimeException(theClass+" not "+xface.getName());
1970        set(name, theClass.getName());
1971      }
1972    
1973      /** 
1974       * Get a local file under a directory named by <i>dirsProp</i> with
1975       * the given <i>path</i>.  If <i>dirsProp</i> contains multiple directories,
1976       * then one is chosen based on <i>path</i>'s hash code.  If the selected
1977       * directory does not exist, an attempt is made to create it.
1978       * 
1979       * @param dirsProp directory in which to locate the file.
1980       * @param path file-path.
1981       * @return local file under the directory with the given path.
1982       */
1983      public Path getLocalPath(String dirsProp, String path)
1984        throws IOException {
1985        String[] dirs = getTrimmedStrings(dirsProp);
1986        int hashCode = path.hashCode();
1987        FileSystem fs = FileSystem.getLocal(this);
1988        for (int i = 0; i < dirs.length; i++) {  // try each local dir
1989          int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
1990          Path file = new Path(dirs[index], path);
1991          Path dir = file.getParent();
1992          if (fs.mkdirs(dir) || fs.exists(dir)) {
1993            return file;
1994          }
1995        }
1996        LOG.warn("Could not make " + path + 
1997                 " in local directories from " + dirsProp);
1998        for(int i=0; i < dirs.length; i++) {
1999          int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
2000          LOG.warn(dirsProp + "[" + index + "]=" + dirs[index]);
2001        }
2002        throw new IOException("No valid local directories in property: "+dirsProp);
2003      }
2004    
2005      /** 
2006       * Get a local file name under a directory named in <i>dirsProp</i> with
2007       * the given <i>path</i>.  If <i>dirsProp</i> contains multiple directories,
2008       * then one is chosen based on <i>path</i>'s hash code.  If the selected
2009       * directory does not exist, an attempt is made to create it.
2010       * 
2011       * @param dirsProp directory in which to locate the file.
2012       * @param path file-path.
2013       * @return local file under the directory with the given path.
2014       */
2015      public File getFile(String dirsProp, String path)
2016        throws IOException {
2017        String[] dirs = getTrimmedStrings(dirsProp);
2018        int hashCode = path.hashCode();
2019        for (int i = 0; i < dirs.length; i++) {  // try each local dir
2020          int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
2021          File file = new File(dirs[index], path);
2022          File dir = file.getParentFile();
2023          if (dir.exists() || dir.mkdirs()) {
2024            return file;
2025          }
2026        }
2027        throw new IOException("No valid local directories in property: "+dirsProp);
2028      }
2029    
2030      /** 
2031       * Get the {@link URL} for the named resource.
2032       * 
2033       * @param name resource name.
2034       * @return the url for the named resource.
2035       */
2036      public URL getResource(String name) {
2037        return classLoader.getResource(name);
2038      }
2039      
2040      /** 
2041       * Get an input stream attached to the configuration resource with the
2042       * given <code>name</code>.
2043       * 
2044       * @param name configuration resource name.
2045       * @return an input stream attached to the resource.
2046       */
2047      public InputStream getConfResourceAsInputStream(String name) {
2048        try {
2049          URL url= getResource(name);
2050    
2051          if (url == null) {
2052            LOG.info(name + " not found");
2053            return null;
2054          } else {
2055            LOG.info("found resource " + name + " at " + url);
2056          }
2057    
2058          return url.openStream();
2059        } catch (Exception e) {
2060          return null;
2061        }
2062      }
2063    
2064      /** 
2065       * Get a {@link Reader} attached to the configuration resource with the
2066       * given <code>name</code>.
2067       * 
2068       * @param name configuration resource name.
2069       * @return a reader attached to the resource.
2070       */
2071      public Reader getConfResourceAsReader(String name) {
2072        try {
2073          URL url= getResource(name);
2074    
2075          if (url == null) {
2076            LOG.info(name + " not found");
2077            return null;
2078          } else {
2079            LOG.info("found resource " + name + " at " + url);
2080          }
2081    
2082          return new InputStreamReader(url.openStream());
2083        } catch (Exception e) {
2084          return null;
2085        }
2086      }
2087    
2088      /**
2089       * Get the set of parameters marked final.
2090       *
2091       * @return final parameter set.
2092       */
2093      public Set<String> getFinalParameters() {
2094        return new HashSet<String>(finalParameters);
2095      }
2096    
2097      protected synchronized Properties getProps() {
2098        if (properties == null) {
2099          properties = new Properties();
2100          HashMap<String, String[]> backup = 
2101            new HashMap<String, String[]>(updatingResource);
2102          loadResources(properties, resources, quietmode);
2103          if (overlay!= null) {
2104            properties.putAll(overlay);
2105            for (Map.Entry<Object,Object> item: overlay.entrySet()) {
2106              String key = (String)item.getKey();
2107              updatingResource.put(key, backup.get(key));
2108            }
2109          }
2110        }
2111        return properties;
2112      }
2113    
2114      /**
2115       * Return the number of keys in the configuration.
2116       *
2117       * @return number of keys in the configuration.
2118       */
2119      public int size() {
2120        return getProps().size();
2121      }
2122    
2123      /**
2124       * Clears all keys from the configuration.
2125       */
2126      public void clear() {
2127        getProps().clear();
2128        getOverlay().clear();
2129      }
2130    
2131      /**
2132       * Get an {@link Iterator} to go through the list of <code>String</code> 
2133       * key-value pairs in the configuration.
2134       * 
2135       * @return an iterator over the entries.
2136       */
2137      @Override
2138      public Iterator<Map.Entry<String, String>> iterator() {
2139        // Get a copy of just the string to string pairs. After the old object
2140        // methods that allow non-strings to be put into configurations are removed,
2141        // we could replace properties with a Map<String,String> and get rid of this
2142        // code.
2143        Map<String,String> result = new HashMap<String,String>();
2144        for(Map.Entry<Object,Object> item: getProps().entrySet()) {
2145          if (item.getKey() instanceof String && 
2146              item.getValue() instanceof String) {
2147            result.put((String) item.getKey(), (String) item.getValue());
2148          }
2149        }
2150        return result.entrySet().iterator();
2151      }
2152    
2153      private Document parse(DocumentBuilder builder, URL url)
2154          throws IOException, SAXException {
2155        if (!quietmode) {
2156          LOG.debug("parsing URL " + url);
2157        }
2158        if (url == null) {
2159          return null;
2160        }
2161        return parse(builder, url.openStream(), url.toString());
2162      }
2163    
2164      private Document parse(DocumentBuilder builder, InputStream is,
2165          String systemId) throws IOException, SAXException {
2166        if (!quietmode) {
2167          LOG.debug("parsing input stream " + is);
2168        }
2169        if (is == null) {
2170          return null;
2171        }
2172        try {
2173          return (systemId == null) ? builder.parse(is) : builder.parse(is,
2174              systemId);
2175        } finally {
2176          is.close();
2177        }
2178      }
2179    
2180      private void loadResources(Properties properties,
2181                                 ArrayList<Resource> resources,
2182                                 boolean quiet) {
2183        if(loadDefaults) {
2184          for (String resource : defaultResources) {
2185            loadResource(properties, new Resource(resource), quiet);
2186          }
2187        
2188          //support the hadoop-site.xml as a deprecated case
2189          if(getResource("hadoop-site.xml")!=null) {
2190            loadResource(properties, new Resource("hadoop-site.xml"), quiet);
2191          }
2192        }
2193        
2194        for (int i = 0; i < resources.size(); i++) {
2195          Resource ret = loadResource(properties, resources.get(i), quiet);
2196          if (ret != null) {
2197            resources.set(i, ret);
2198          }
2199        }
2200      }
2201      
2202      private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) {
2203        String name = UNKNOWN_RESOURCE;
2204        try {
2205          Object resource = wrapper.getResource();
2206          name = wrapper.getName();
2207          
2208          DocumentBuilderFactory docBuilderFactory 
2209            = DocumentBuilderFactory.newInstance();
2210          //ignore all comments inside the xml file
2211          docBuilderFactory.setIgnoringComments(true);
2212    
2213          //allow includes in the xml file
2214          docBuilderFactory.setNamespaceAware(true);
2215          try {
2216              docBuilderFactory.setXIncludeAware(true);
2217          } catch (UnsupportedOperationException e) {
2218            LOG.error("Failed to set setXIncludeAware(true) for parser "
2219                    + docBuilderFactory
2220                    + ":" + e,
2221                    e);
2222          }
2223          DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
2224          Document doc = null;
2225          Element root = null;
2226          boolean returnCachedProperties = false;
2227          
2228          if (resource instanceof URL) {                  // an URL resource
2229            doc = parse(builder, (URL)resource);
2230          } else if (resource instanceof String) {        // a CLASSPATH resource
2231            URL url = getResource((String)resource);
2232            doc = parse(builder, url);
2233          } else if (resource instanceof Path) {          // a file resource
2234            // Can't use FileSystem API or we get an infinite loop
2235            // since FileSystem uses Configuration API.  Use java.io.File instead.
2236            File file = new File(((Path)resource).toUri().getPath())
2237              .getAbsoluteFile();
2238            if (file.exists()) {
2239              if (!quiet) {
2240                LOG.debug("parsing File " + file);
2241              }
2242              doc = parse(builder, new BufferedInputStream(
2243                  new FileInputStream(file)), ((Path)resource).toString());
2244            }
2245          } else if (resource instanceof InputStream) {
2246            doc = parse(builder, (InputStream) resource, null);
2247            returnCachedProperties = true;
2248          } else if (resource instanceof Properties) {
2249            overlay(properties, (Properties)resource);
2250          } else if (resource instanceof Element) {
2251            root = (Element)resource;
2252          }
2253    
2254          if (root == null) {
2255            if (doc == null) {
2256              if (quiet) {
2257                return null;
2258              }
2259              throw new RuntimeException(resource + " not found");
2260            }
2261            root = doc.getDocumentElement();
2262          }
2263          Properties toAddTo = properties;
2264          if(returnCachedProperties) {
2265            toAddTo = new Properties();
2266          }
2267          if (!"configuration".equals(root.getTagName()))
2268            LOG.fatal("bad conf file: top-level element not <configuration>");
2269          NodeList props = root.getChildNodes();
2270          DeprecationContext deprecations = deprecationContext.get();
2271          for (int i = 0; i < props.getLength(); i++) {
2272            Node propNode = props.item(i);
2273            if (!(propNode instanceof Element))
2274              continue;
2275            Element prop = (Element)propNode;
2276            if ("configuration".equals(prop.getTagName())) {
2277              loadResource(toAddTo, new Resource(prop, name), quiet);
2278              continue;
2279            }
2280            if (!"property".equals(prop.getTagName()))
2281              LOG.warn("bad conf file: element not <property>");
2282            NodeList fields = prop.getChildNodes();
2283            String attr = null;
2284            String value = null;
2285            boolean finalParameter = false;
2286            LinkedList<String> source = new LinkedList<String>();
2287            for (int j = 0; j < fields.getLength(); j++) {
2288              Node fieldNode = fields.item(j);
2289              if (!(fieldNode instanceof Element))
2290                continue;
2291              Element field = (Element)fieldNode;
2292              if ("name".equals(field.getTagName()) && field.hasChildNodes())
2293                attr = StringInterner.weakIntern(
2294                    ((Text)field.getFirstChild()).getData().trim());
2295              if ("value".equals(field.getTagName()) && field.hasChildNodes())
2296                value = StringInterner.weakIntern(
2297                    ((Text)field.getFirstChild()).getData());
2298              if ("final".equals(field.getTagName()) && field.hasChildNodes())
2299                finalParameter = "true".equals(((Text)field.getFirstChild()).getData());
2300              if ("source".equals(field.getTagName()) && field.hasChildNodes())
2301                source.add(StringInterner.weakIntern(
2302                    ((Text)field.getFirstChild()).getData()));
2303            }
2304            source.add(name);
2305            
2306            // Ignore this parameter if it has already been marked as 'final'
2307            if (attr != null) {
2308              if (deprecations.getDeprecatedKeyMap().containsKey(attr)) {
2309                DeprecatedKeyInfo keyInfo =
2310                    deprecations.getDeprecatedKeyMap().get(attr);
2311                keyInfo.clearAccessed();
2312                for (String key:keyInfo.newKeys) {
2313                  // update new keys with deprecated key's value 
2314                  loadProperty(toAddTo, name, key, value, finalParameter, 
2315                      source.toArray(new String[source.size()]));
2316                }
2317              }
2318              else {
2319                loadProperty(toAddTo, name, attr, value, finalParameter, 
2320                    source.toArray(new String[source.size()]));
2321              }
2322            }
2323          }
2324          
2325          if (returnCachedProperties) {
2326            overlay(properties, toAddTo);
2327            return new Resource(toAddTo, name);
2328          }
2329          return null;
2330        } catch (IOException e) {
2331          LOG.fatal("error parsing conf " + name, e);
2332          throw new RuntimeException(e);
2333        } catch (DOMException e) {
2334          LOG.fatal("error parsing conf " + name, e);
2335          throw new RuntimeException(e);
2336        } catch (SAXException e) {
2337          LOG.fatal("error parsing conf " + name, e);
2338          throw new RuntimeException(e);
2339        } catch (ParserConfigurationException e) {
2340          LOG.fatal("error parsing conf " + name , e);
2341          throw new RuntimeException(e);
2342        }
2343      }
2344    
2345      private void overlay(Properties to, Properties from) {
2346        for (Entry<Object, Object> entry: from.entrySet()) {
2347          to.put(entry.getKey(), entry.getValue());
2348        }
2349      }
2350      
2351      private void loadProperty(Properties properties, String name, String attr,
2352          String value, boolean finalParameter, String[] source) {
2353        if (value != null) {
2354          if (!finalParameters.contains(attr)) {
2355            properties.setProperty(attr, value);
2356            updatingResource.put(attr, source);
2357          } else {
2358            LOG.warn(name+":an attempt to override final parameter: "+attr
2359                +";  Ignoring.");
2360          }
2361        }
2362        if (finalParameter) {
2363          finalParameters.add(attr);
2364        }
2365      }
2366    
2367      /** 
2368       * Write out the non-default properties in this configuration to the given
2369       * {@link OutputStream} using UTF-8 encoding.
2370       * 
2371       * @param out the output stream to write to.
2372       */
2373      public void writeXml(OutputStream out) throws IOException {
2374        writeXml(new OutputStreamWriter(out, "UTF-8"));
2375      }
2376    
2377      /** 
2378       * Write out the non-default properties in this configuration to the given
2379       * {@link Writer}.
2380       * 
2381       * @param out the writer to write to.
2382       */
2383      public void writeXml(Writer out) throws IOException {
2384        Document doc = asXmlDocument();
2385    
2386        try {
2387          DOMSource source = new DOMSource(doc);
2388          StreamResult result = new StreamResult(out);
2389          TransformerFactory transFactory = TransformerFactory.newInstance();
2390          Transformer transformer = transFactory.newTransformer();
2391    
2392          // Important to not hold Configuration log while writing result, since
2393          // 'out' may be an HDFS stream which needs to lock this configuration
2394          // from another thread.
2395          transformer.transform(source, result);
2396        } catch (TransformerException te) {
2397          throw new IOException(te);
2398        }
2399      }
2400    
2401      /**
2402       * Return the XML DOM corresponding to this Configuration.
2403       */
2404      private synchronized Document asXmlDocument() throws IOException {
2405        Document doc;
2406        try {
2407          doc =
2408            DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
2409        } catch (ParserConfigurationException pe) {
2410          throw new IOException(pe);
2411        }
2412        Element conf = doc.createElement("configuration");
2413        doc.appendChild(conf);
2414        conf.appendChild(doc.createTextNode("\n"));
2415        handleDeprecation(); //ensure properties is set and deprecation is handled
2416        for (Enumeration<Object> e = properties.keys(); e.hasMoreElements();) {
2417          String name = (String)e.nextElement();
2418          Object object = properties.get(name);
2419          String value = null;
2420          if (object instanceof String) {
2421            value = (String) object;
2422          }else {
2423            continue;
2424          }
2425          Element propNode = doc.createElement("property");
2426          conf.appendChild(propNode);
2427    
2428          Element nameNode = doc.createElement("name");
2429          nameNode.appendChild(doc.createTextNode(name));
2430          propNode.appendChild(nameNode);
2431    
2432          Element valueNode = doc.createElement("value");
2433          valueNode.appendChild(doc.createTextNode(value));
2434          propNode.appendChild(valueNode);
2435    
2436          if (updatingResource != null) {
2437            String[] sources = updatingResource.get(name);
2438            if(sources != null) {
2439              for(String s : sources) {
2440                Element sourceNode = doc.createElement("source");
2441                sourceNode.appendChild(doc.createTextNode(s));
2442                propNode.appendChild(sourceNode);
2443              }
2444            }
2445          }
2446          
2447          conf.appendChild(doc.createTextNode("\n"));
2448        }
2449        return doc;
2450      }
2451    
2452      /**
2453       *  Writes out all the parameters and their properties (final and resource) to
2454       *  the given {@link Writer}
2455       *  The format of the output would be 
2456       *  { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
2457       *  key2.isFinal,key2.resource}... ] } 
2458       *  It does not output the parameters of the configuration object which is 
2459       *  loaded from an input stream.
2460       * @param out the Writer to write to
2461       * @throws IOException
2462       */
2463      public static void dumpConfiguration(Configuration config,
2464          Writer out) throws IOException {
2465        JsonFactory dumpFactory = new JsonFactory();
2466        JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
2467        dumpGenerator.writeStartObject();
2468        dumpGenerator.writeFieldName("properties");
2469        dumpGenerator.writeStartArray();
2470        dumpGenerator.flush();
2471        synchronized (config) {
2472          for (Map.Entry<Object,Object> item: config.getProps().entrySet()) {
2473            dumpGenerator.writeStartObject();
2474            dumpGenerator.writeStringField("key", (String) item.getKey());
2475            dumpGenerator.writeStringField("value", 
2476                                           config.get((String) item.getKey()));
2477            dumpGenerator.writeBooleanField("isFinal",
2478                                            config.finalParameters.contains(item.getKey()));
2479            String[] resources = config.updatingResource.get(item.getKey());
2480            String resource = UNKNOWN_RESOURCE;
2481            if(resources != null && resources.length > 0) {
2482              resource = resources[0];
2483            }
2484            dumpGenerator.writeStringField("resource", resource);
2485            dumpGenerator.writeEndObject();
2486          }
2487        }
2488        dumpGenerator.writeEndArray();
2489        dumpGenerator.writeEndObject();
2490        dumpGenerator.flush();
2491      }
2492      
2493      /**
2494       * Get the {@link ClassLoader} for this job.
2495       * 
2496       * @return the correct class loader.
2497       */
2498      public ClassLoader getClassLoader() {
2499        return classLoader;
2500      }
2501      
2502      /**
2503       * Set the class loader that will be used to load the various objects.
2504       * 
2505       * @param classLoader the new class loader.
2506       */
2507      public void setClassLoader(ClassLoader classLoader) {
2508        this.classLoader = classLoader;
2509      }
2510      
2511      @Override
2512      public String toString() {
2513        StringBuilder sb = new StringBuilder();
2514        sb.append("Configuration: ");
2515        if(loadDefaults) {
2516          toString(defaultResources, sb);
2517          if(resources.size()>0) {
2518            sb.append(", ");
2519          }
2520        }
2521        toString(resources, sb);
2522        return sb.toString();
2523      }
2524      
2525      private <T> void toString(List<T> resources, StringBuilder sb) {
2526        ListIterator<T> i = resources.listIterator();
2527        while (i.hasNext()) {
2528          if (i.nextIndex() != 0) {
2529            sb.append(", ");
2530          }
2531          sb.append(i.next());
2532        }
2533      }
2534    
2535      /** 
2536       * Set the quietness-mode. 
2537       * 
2538       * In the quiet-mode, error and informational messages might not be logged.
2539       * 
2540       * @param quietmode <code>true</code> to set quiet-mode on, <code>false</code>
2541       *              to turn it off.
2542       */
2543      public synchronized void setQuietMode(boolean quietmode) {
2544        this.quietmode = quietmode;
2545      }
2546    
2547      synchronized boolean getQuietMode() {
2548        return this.quietmode;
2549      }
2550      
2551      /** For debugging.  List non-default properties to the terminal and exit. */
2552      public static void main(String[] args) throws Exception {
2553        new Configuration().writeXml(System.out);
2554      }
2555    
2556      @Override
2557      public void readFields(DataInput in) throws IOException {
2558        clear();
2559        int size = WritableUtils.readVInt(in);
2560        for(int i=0; i < size; ++i) {
2561          String key = org.apache.hadoop.io.Text.readString(in);
2562          String value = org.apache.hadoop.io.Text.readString(in);
2563          set(key, value); 
2564          String sources[] = WritableUtils.readCompressedStringArray(in);
2565          updatingResource.put(key, sources);
2566        }
2567      }
2568    
2569      //@Override
2570      @Override
2571      public void write(DataOutput out) throws IOException {
2572        Properties props = getProps();
2573        WritableUtils.writeVInt(out, props.size());
2574        for(Map.Entry<Object, Object> item: props.entrySet()) {
2575          org.apache.hadoop.io.Text.writeString(out, (String) item.getKey());
2576          org.apache.hadoop.io.Text.writeString(out, (String) item.getValue());
2577          WritableUtils.writeCompressedStringArray(out, 
2578              updatingResource.get(item.getKey()));
2579        }
2580      }
2581      
2582      /**
2583       * get keys matching the the regex 
2584       * @param regex
2585       * @return Map<String,String> with matching keys
2586       */
2587      public Map<String,String> getValByRegex(String regex) {
2588        Pattern p = Pattern.compile(regex);
2589    
2590        Map<String,String> result = new HashMap<String,String>();
2591        Matcher m;
2592    
2593        for(Map.Entry<Object,Object> item: getProps().entrySet()) {
2594          if (item.getKey() instanceof String && 
2595              item.getValue() instanceof String) {
2596            m = p.matcher((String)item.getKey());
2597            if(m.find()) { // match
2598              result.put((String) item.getKey(), (String) item.getValue());
2599            }
2600          }
2601        }
2602        return result;
2603      }
2604    
2605      /**
2606       * A unique class which is used as a sentinel value in the caching
2607       * for getClassByName. {@see Configuration#getClassByNameOrNull(String)}
2608       */
2609      private static abstract class NegativeCacheSentinel {}
2610    
2611      public static void dumpDeprecatedKeys() {
2612        DeprecationContext deprecations = deprecationContext.get();
2613        for (Map.Entry<String, DeprecatedKeyInfo> entry :
2614            deprecations.getDeprecatedKeyMap().entrySet()) {
2615          StringBuilder newKeys = new StringBuilder();
2616          for (String newKey : entry.getValue().newKeys) {
2617            newKeys.append(newKey).append("\t");
2618          }
2619          System.out.println(entry.getKey() + "\t" + newKeys.toString());
2620        }
2621      }
2622    
2623      /**
2624       * Returns whether or not a deprecated name has been warned. If the name is not
2625       * deprecated then always return false
2626       */
2627      public static boolean hasWarnedDeprecation(String name) {
2628        DeprecationContext deprecations = deprecationContext.get();
2629        if(deprecations.getDeprecatedKeyMap().containsKey(name)) {
2630          if(deprecations.getDeprecatedKeyMap().get(name).accessed.get()) {
2631            return true;
2632          }
2633        }
2634        return false;
2635      }
2636    }