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