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