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