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