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