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