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