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