1 /*
   2  * Copyright (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 
  28 import java.io.IOException;
  29 import java.io.PrintStream;
  30 import java.io.PrintWriter;
  31 import java.io.InputStream;
  32 import java.io.OutputStream;
  33 import java.io.Reader;
  34 import java.io.Writer;
  35 import java.io.OutputStreamWriter;
  36 import java.io.BufferedWriter;
  37 import java.io.ObjectInputStream;
  38 import java.io.ObjectOutputStream;
  39 import java.io.StreamCorruptedException;
  40 import java.io.UnsupportedEncodingException;
  41 import java.nio.charset.Charset;
  42 import java.nio.charset.IllegalCharsetNameException;
  43 import java.nio.charset.UnsupportedCharsetException;
  44 import java.util.concurrent.ConcurrentHashMap;
  45 import java.util.function.BiConsumer;
  46 import java.util.function.BiFunction;
  47 import java.util.function.Function;
  48 
  49 import jdk.internal.access.SharedSecrets;
  50 import jdk.internal.misc.Unsafe;
  51 import jdk.internal.util.xml.PropertiesDefaultHandler;
  52 
  53 /**
  54  * The {@code Properties} class represents a persistent set of
  55  * properties. The {@code Properties} can be saved to a stream
  56  * or loaded from a stream. Each key and its corresponding value in
  57  * the property list is a string.
  58  * <p>
  59  * A property list can contain another property list as its
  60  * "defaults"; this second property list is searched if
  61  * the property key is not found in the original property list.
  62  * <p>
  63  * Because {@code Properties} inherits from {@code Hashtable}, the
  64  * {@code put} and {@code putAll} methods can be applied to a
  65  * {@code Properties} object.  Their use is strongly discouraged as they
  66  * allow the caller to insert entries whose keys or values are not
  67  * {@code Strings}.  The {@code setProperty} method should be used
  68  * instead.  If the {@code store} or {@code save} method is called
  69  * on a "compromised" {@code Properties} object that contains a
  70  * non-{@code String} key or value, the call will fail. Similarly,
  71  * the call to the {@code propertyNames} or {@code list} method
  72  * will fail if it is called on a "compromised" {@code Properties}
  73  * object that contains a non-{@code String} key.
  74  *
  75  * <p>
  76  * The iterators returned by the {@code iterator} method of this class's
  77  * "collection views" (that is, {@code entrySet()}, {@code keySet()}, and
  78  * {@code values()}) may not fail-fast (unlike the Hashtable implementation).
  79  * These iterators are guaranteed to traverse elements as they existed upon
  80  * construction exactly once, and may (but are not guaranteed to) reflect any
  81  * modifications subsequent to construction.
  82  * <p>
  83  * The {@link #load(java.io.Reader) load(Reader)} {@code /}
  84  * {@link #store(java.io.Writer, java.lang.String) store(Writer, String)}
  85  * methods load and store properties from and to a character based stream
  86  * in a simple line-oriented format specified below.
  87  *
  88  * The {@link #load(java.io.InputStream) load(InputStream)} {@code /}
  89  * {@link #store(java.io.OutputStream, java.lang.String) store(OutputStream, String)}
  90  * methods work the same way as the load(Reader)/store(Writer, String) pair, except
  91  * the input/output stream is encoded in ISO 8859-1 character encoding.
  92  * Characters that cannot be directly represented in this encoding can be written using
  93  * Unicode escapes as defined in section 3.3 of
  94  * <cite>The Java&trade; Language Specification</cite>;
  95  * only a single 'u' character is allowed in an escape
  96  * sequence.
  97  *
  98  * <p> The {@link #loadFromXML(InputStream)} and {@link
  99  * #storeToXML(OutputStream, String, String)} methods load and store properties
 100  * in a simple XML format.  By default the UTF-8 character encoding is used,
 101  * however a specific encoding may be specified if required. Implementations
 102  * are required to support UTF-8 and UTF-16 and may support other encodings.
 103  * An XML properties document has the following DOCTYPE declaration:
 104  *
 105  * <pre>
 106  * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;
 107  * </pre>
 108  * Note that the system URI (http://java.sun.com/dtd/properties.dtd) is
 109  * <i>not</i> accessed when exporting or importing properties; it merely
 110  * serves as a string to uniquely identify the DTD, which is:
 111  * <pre>
 112  *    &lt;?xml version="1.0" encoding="UTF-8"?&gt;
 113  *
 114  *    &lt;!-- DTD for properties --&gt;
 115  *
 116  *    &lt;!ELEMENT properties ( comment?, entry* ) &gt;
 117  *
 118  *    &lt;!ATTLIST properties version CDATA #FIXED "1.0"&gt;
 119  *
 120  *    &lt;!ELEMENT comment (#PCDATA) &gt;
 121  *
 122  *    &lt;!ELEMENT entry (#PCDATA) &gt;
 123  *
 124  *    &lt;!ATTLIST entry key CDATA #REQUIRED&gt;
 125  * </pre>
 126  *
 127  * <p>This class is thread-safe: multiple threads can share a single
 128  * {@code Properties} object without the need for external synchronization.
 129  *
 130  * @apiNote
 131  * The {@code Properties} class does not inherit the concept of a load factor
 132  * from its superclass, {@code Hashtable}.
 133  *
 134  * @author  Arthur van Hoff
 135  * @author  Michael McCloskey
 136  * @author  Xueming Shen
 137  * @since   1.0
 138  */
 139 public
 140 class Properties extends Hashtable<Object,Object> {
 141     /**
 142      * use serialVersionUID from JDK 1.1.X for interoperability
 143      */
 144     private static final long serialVersionUID = 4112578634029874840L;
 145 
 146     private static final Unsafe UNSAFE = Unsafe.getUnsafe();
 147 
 148     /**
 149      * A property list that contains default values for any keys not
 150      * found in this property list.
 151      *
 152      * @serial
 153      */
 154     protected volatile Properties defaults;
 155 
 156     /**
 157      * Properties does not store values in its inherited Hashtable, but instead
 158      * in an internal ConcurrentHashMap.  Synchronization is omitted from
 159      * simple read operations.  Writes and bulk operations remain synchronized,
 160      * as in Hashtable.
 161      */
 162     private transient volatile ConcurrentHashMap<Object, Object> map;
 163 
 164     /**
 165      * Creates an empty property list with no default values.
 166      *
 167      * @implNote The initial capacity of a {@code Properties} object created
 168      * with this constructor is unspecified.
 169      */
 170     public Properties() {
 171         this(null, 8);
 172     }
 173 
 174     /**
 175      * Creates an empty property list with no default values, and with an
 176      * initial size accommodating the specified number of elements without the
 177      * need to dynamically resize.
 178      *
 179      * @param  initialCapacity the {@code Properties} will be sized to
 180      *         accommodate this many elements
 181      * @throws IllegalArgumentException if the initial capacity is less than
 182      *         zero.
 183      */
 184     public Properties(int initialCapacity) {
 185         this(null, initialCapacity);
 186     }
 187 
 188     /**
 189      * Creates an empty property list with the specified defaults.
 190      *
 191      * @implNote The initial capacity of a {@code Properties} object created
 192      * with this constructor is unspecified.
 193      *
 194      * @param   defaults   the defaults.
 195      */
 196     public Properties(Properties defaults) {
 197         this(defaults, 8);
 198     }
 199 
 200     private Properties(Properties defaults, int initialCapacity) {
 201         // use package-private constructor to
 202         // initialize unused fields with dummy values
 203         super((Void) null);
 204         map = new ConcurrentHashMap<>(initialCapacity);
 205         this.defaults = defaults;
 206 
 207         // Ensure writes can't be reordered
 208         UNSAFE.storeFence();
 209     }
 210 
 211     /**
 212      * Calls the {@code Hashtable} method {@code put}. Provided for
 213      * parallelism with the {@code getProperty} method. Enforces use of
 214      * strings for property keys and values. The value returned is the
 215      * result of the {@code Hashtable} call to {@code put}.
 216      *
 217      * @param key the key to be placed into this property list.
 218      * @param value the value corresponding to {@code key}.
 219      * @return     the previous value of the specified key in this property
 220      *             list, or {@code null} if it did not have one.
 221      * @see #getProperty
 222      * @since    1.2
 223      */
 224     public synchronized Object setProperty(String key, String value) {
 225         return put(key, value);
 226     }
 227 
 228 
 229     /**
 230      * Reads a property list (key and element pairs) from the input
 231      * character stream in a simple line-oriented format.
 232      * <p>
 233      * Properties are processed in terms of lines. There are two
 234      * kinds of line, <i>natural lines</i> and <i>logical lines</i>.
 235      * A natural line is defined as a line of
 236      * characters that is terminated either by a set of line terminator
 237      * characters ({@code \n} or {@code \r} or {@code \r\n})
 238      * or by the end of the stream. A natural line may be either a blank line,
 239      * a comment line, or hold all or some of a key-element pair. A logical
 240      * line holds all the data of a key-element pair, which may be spread
 241      * out across several adjacent natural lines by escaping
 242      * the line terminator sequence with a backslash character
 243      * {@code \}.  Note that a comment line cannot be extended
 244      * in this manner; every natural line that is a comment must have
 245      * its own comment indicator, as described below. Lines are read from
 246      * input until the end of the stream is reached.
 247      *
 248      * <p>
 249      * A natural line that contains only white space characters is
 250      * considered blank and is ignored.  A comment line has an ASCII
 251      * {@code '#'} or {@code '!'} as its first non-white
 252      * space character; comment lines are also ignored and do not
 253      * encode key-element information.  In addition to line
 254      * terminators, this format considers the characters space
 255      * ({@code ' '}, {@code '\u005Cu0020'}), tab
 256      * ({@code '\t'}, {@code '\u005Cu0009'}), and form feed
 257      * ({@code '\f'}, {@code '\u005Cu000C'}) to be white
 258      * space.
 259      *
 260      * <p>
 261      * If a logical line is spread across several natural lines, the
 262      * backslash escaping the line terminator sequence, the line
 263      * terminator sequence, and any white space at the start of the
 264      * following line have no affect on the key or element values.
 265      * The remainder of the discussion of key and element parsing
 266      * (when loading) will assume all the characters constituting
 267      * the key and element appear on a single natural line after
 268      * line continuation characters have been removed.  Note that
 269      * it is <i>not</i> sufficient to only examine the character
 270      * preceding a line terminator sequence to decide if the line
 271      * terminator is escaped; there must be an odd number of
 272      * contiguous backslashes for the line terminator to be escaped.
 273      * Since the input is processed from left to right, a
 274      * non-zero even number of 2<i>n</i> contiguous backslashes
 275      * before a line terminator (or elsewhere) encodes <i>n</i>
 276      * backslashes after escape processing.
 277      *
 278      * <p>
 279      * The key contains all of the characters in the line starting
 280      * with the first non-white space character and up to, but not
 281      * including, the first unescaped {@code '='},
 282      * {@code ':'}, or white space character other than a line
 283      * terminator. All of these key termination characters may be
 284      * included in the key by escaping them with a preceding backslash
 285      * character; for example,<p>
 286      *
 287      * {@code \:\=}<p>
 288      *
 289      * would be the two-character key {@code ":="}.  Line
 290      * terminator characters can be included using {@code \r} and
 291      * {@code \n} escape sequences.  Any white space after the
 292      * key is skipped; if the first non-white space character after
 293      * the key is {@code '='} or {@code ':'}, then it is
 294      * ignored and any white space characters after it are also
 295      * skipped.  All remaining characters on the line become part of
 296      * the associated element string; if there are no remaining
 297      * characters, the element is the empty string
 298      * {@code ""}.  Once the raw character sequences
 299      * constituting the key and element are identified, escape
 300      * processing is performed as described above.
 301      *
 302      * <p>
 303      * As an example, each of the following three lines specifies the key
 304      * {@code "Truth"} and the associated element value
 305      * {@code "Beauty"}:
 306      * <pre>
 307      * Truth = Beauty
 308      *  Truth:Beauty
 309      * Truth                    :Beauty
 310      * </pre>
 311      * As another example, the following three lines specify a single
 312      * property:
 313      * <pre>
 314      * fruits                           apple, banana, pear, \
 315      *                                  cantaloupe, watermelon, \
 316      *                                  kiwi, mango
 317      * </pre>
 318      * The key is {@code "fruits"} and the associated element is:
 319      * <pre>"apple, banana, pear, cantaloupe, watermelon, kiwi, mango"</pre>
 320      * Note that a space appears before each {@code \} so that a space
 321      * will appear after each comma in the final result; the {@code \},
 322      * line terminator, and leading white space on the continuation line are
 323      * merely discarded and are <i>not</i> replaced by one or more other
 324      * characters.
 325      * <p>
 326      * As a third example, the line:
 327      * <pre>cheeses
 328      * </pre>
 329      * specifies that the key is {@code "cheeses"} and the associated
 330      * element is the empty string {@code ""}.
 331      * <p>
 332      * <a id="unicodeescapes"></a>
 333      * Characters in keys and elements can be represented in escape
 334      * sequences similar to those used for character and string literals
 335      * (see sections 3.3 and 3.10.6 of
 336      * <cite>The Java&trade; Language Specification</cite>).
 337      *
 338      * The differences from the character escape sequences and Unicode
 339      * escapes used for characters and strings are:
 340      *
 341      * <ul>
 342      * <li> Octal escapes are not recognized.
 343      *
 344      * <li> The character sequence {@code \b} does <i>not</i>
 345      * represent a backspace character.
 346      *
 347      * <li> The method does not treat a backslash character,
 348      * {@code \}, before a non-valid escape character as an
 349      * error; the backslash is silently dropped.  For example, in a
 350      * Java string the sequence {@code "\z"} would cause a
 351      * compile time error.  In contrast, this method silently drops
 352      * the backslash.  Therefore, this method treats the two character
 353      * sequence {@code "\b"} as equivalent to the single
 354      * character {@code 'b'}.
 355      *
 356      * <li> Escapes are not necessary for single and double quotes;
 357      * however, by the rule above, single and double quote characters
 358      * preceded by a backslash still yield single and double quote
 359      * characters, respectively.
 360      *
 361      * <li> Only a single 'u' character is allowed in a Unicode escape
 362      * sequence.
 363      *
 364      * </ul>
 365      * <p>
 366      * The specified stream remains open after this method returns.
 367      *
 368      * @param   reader   the input character stream.
 369      * @throws  IOException  if an error occurred when reading from the
 370      *          input stream.
 371      * @throws  IllegalArgumentException if a malformed Unicode escape
 372      *          appears in the input.
 373      * @throws  NullPointerException if {@code reader} is null.
 374      * @since   1.6
 375      */
 376     public synchronized void load(Reader reader) throws IOException {
 377         Objects.requireNonNull(reader, "reader parameter is null");
 378         load0(new LineReader(reader));
 379     }
 380 
 381     /**
 382      * Reads a property list (key and element pairs) from the input
 383      * byte stream. The input stream is in a simple line-oriented
 384      * format as specified in
 385      * {@link #load(java.io.Reader) load(Reader)} and is assumed to use
 386      * the ISO 8859-1 character encoding; that is each byte is one Latin1
 387      * character. Characters not in Latin1, and certain special characters,
 388      * are represented in keys and elements using Unicode escapes as defined in
 389      * section 3.3 of
 390      * <cite>The Java&trade; Language Specification</cite>.
 391      * <p>
 392      * The specified stream remains open after this method returns.
 393      *
 394      * @param      inStream   the input stream.
 395      * @exception  IOException  if an error occurred when reading from the
 396      *             input stream.
 397      * @throws     IllegalArgumentException if the input stream contains a
 398      *             malformed Unicode escape sequence.
 399      * @throws     NullPointerException if {@code inStream} is null.
 400      * @since 1.2
 401      */
 402     public synchronized void load(InputStream inStream) throws IOException {
 403         Objects.requireNonNull(inStream, "inStream parameter is null");
 404         load0(new LineReader(inStream));
 405     }
 406 
 407     private void load0 (LineReader lr) throws IOException {
 408         char[] convtBuf = new char[1024];
 409         int limit;
 410         int keyLen;
 411         int valueStart;
 412         char c;
 413         boolean hasSep;
 414         boolean precedingBackslash;
 415 
 416         while ((limit = lr.readLine()) >= 0) {
 417             c = 0;
 418             keyLen = 0;
 419             valueStart = limit;
 420             hasSep = false;
 421 
 422             //System.out.println("line=<" + new String(lineBuf, 0, limit) + ">");
 423             precedingBackslash = false;
 424             while (keyLen < limit) {
 425                 c = lr.lineBuf[keyLen];
 426                 //need check if escaped.
 427                 if ((c == '=' ||  c == ':') && !precedingBackslash) {
 428                     valueStart = keyLen + 1;
 429                     hasSep = true;
 430                     break;
 431                 } else if ((c == ' ' || c == '\t' ||  c == '\f') && !precedingBackslash) {
 432                     valueStart = keyLen + 1;
 433                     break;
 434                 }
 435                 if (c == '\\') {
 436                     precedingBackslash = !precedingBackslash;
 437                 } else {
 438                     precedingBackslash = false;
 439                 }
 440                 keyLen++;
 441             }
 442             while (valueStart < limit) {
 443                 c = lr.lineBuf[valueStart];
 444                 if (c != ' ' && c != '\t' &&  c != '\f') {
 445                     if (!hasSep && (c == '=' ||  c == ':')) {
 446                         hasSep = true;
 447                     } else {
 448                         break;
 449                     }
 450                 }
 451                 valueStart++;
 452             }
 453             String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
 454             String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
 455             put(key, value);
 456         }
 457     }
 458 
 459     /* Read in a "logical line" from an InputStream/Reader, skip all comment
 460      * and blank lines and filter out those leading whitespace characters
 461      * (\u0020, \u0009 and \u000c) from the beginning of a "natural line".
 462      * Method returns the char length of the "logical line" and stores
 463      * the line in "lineBuf".
 464      */
 465     class LineReader {
 466         public LineReader(InputStream inStream) {
 467             this.inStream = inStream;
 468             inByteBuf = new byte[8192];
 469         }
 470 
 471         public LineReader(Reader reader) {
 472             this.reader = reader;
 473             inCharBuf = new char[8192];
 474         }
 475 
 476         byte[] inByteBuf;
 477         char[] inCharBuf;
 478         char[] lineBuf = new char[1024];
 479         int inLimit = 0;
 480         int inOff = 0;
 481         InputStream inStream;
 482         Reader reader;
 483 
 484         int readLine() throws IOException {
 485             int len = 0;
 486             char c = 0;
 487 
 488             boolean skipWhiteSpace = true;
 489             boolean isCommentLine = false;
 490             boolean isNewLine = true;
 491             boolean appendedLineBegin = false;
 492             boolean precedingBackslash = false;
 493             boolean skipLF = false;
 494 
 495             while (true) {
 496                 if (inOff >= inLimit) {
 497                     inLimit = (inStream==null)?reader.read(inCharBuf)
 498                                               :inStream.read(inByteBuf);
 499                     inOff = 0;
 500                     if (inLimit <= 0) {
 501                         if (len == 0 || isCommentLine) {
 502                             return -1;
 503                         }
 504                         if (precedingBackslash) {
 505                             len--;
 506                         }
 507                         return len;
 508                     }
 509                 }
 510                 if (inStream != null) {
 511                     //The line below is equivalent to calling a
 512                     //ISO8859-1 decoder.
 513                     c = (char)(inByteBuf[inOff++] & 0xFF);
 514                 } else {
 515                     c = inCharBuf[inOff++];
 516                 }
 517                 if (skipLF) {
 518                     skipLF = false;
 519                     if (c == '\n') {
 520                         continue;
 521                     }
 522                 }
 523                 if (skipWhiteSpace) {
 524                     if (c == ' ' || c == '\t' || c == '\f') {
 525                         continue;
 526                     }
 527                     if (!appendedLineBegin && (c == '\r' || c == '\n')) {
 528                         continue;
 529                     }
 530                     skipWhiteSpace = false;
 531                     appendedLineBegin = false;
 532                 }
 533                 if (isNewLine) {
 534                     isNewLine = false;
 535                     if (c == '#' || c == '!') {
 536                         // Comment, quickly consume the rest of the line,
 537                         // resume on line-break and backslash.
 538                         if (inStream != null) {
 539                             while (inOff < inLimit) {
 540                                 byte b = inByteBuf[inOff++];
 541                                 if (b == '\n' || b == '\r' || b == '\\') {
 542                                     c = (char)(b & 0xFF);
 543                                     break;
 544                                 }
 545                             }
 546                         } else {
 547                             while (inOff < inLimit) {
 548                                 c = inCharBuf[inOff++];
 549                                 if (c == '\n' || c == '\r' || c == '\\') {
 550                                     break;
 551                                 }
 552                             }
 553                         }
 554                         isCommentLine = true;
 555                     }
 556                 }
 557 
 558                 if (c != '\n' && c != '\r') {
 559                     lineBuf[len++] = c;
 560                     if (len == lineBuf.length) {
 561                         int newLength = lineBuf.length * 2;
 562                         if (newLength < 0) {
 563                             newLength = Integer.MAX_VALUE;
 564                         }
 565                         char[] buf = new char[newLength];
 566                         System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length);
 567                         lineBuf = buf;
 568                     }
 569                     //flip the preceding backslash flag
 570                     if (c == '\\') {
 571                         precedingBackslash = !precedingBackslash;
 572                     } else {
 573                         precedingBackslash = false;
 574                     }
 575                 }
 576                 else {
 577                     // reached EOL
 578                     if (isCommentLine || len == 0) {
 579                         isCommentLine = false;
 580                         isNewLine = true;
 581                         skipWhiteSpace = true;
 582                         len = 0;
 583                         continue;
 584                     }
 585                     if (inOff >= inLimit) {
 586                         inLimit = (inStream==null)
 587                                   ?reader.read(inCharBuf)
 588                                   :inStream.read(inByteBuf);
 589                         inOff = 0;
 590                         if (inLimit <= 0) {
 591                             if (precedingBackslash) {
 592                                 len--;
 593                             }
 594                             return len;
 595                         }
 596                     }
 597                     if (precedingBackslash) {
 598                         len -= 1;
 599                         //skip the leading whitespace characters in following line
 600                         skipWhiteSpace = true;
 601                         appendedLineBegin = true;
 602                         precedingBackslash = false;
 603                         if (c == '\r') {
 604                             skipLF = true;
 605                         }
 606                     } else {
 607                         return len;
 608                     }
 609                 }
 610             }
 611         }
 612     }
 613 
 614     /*
 615      * Converts encoded \uxxxx to unicode chars
 616      * and changes special saved chars to their original forms
 617      */
 618     private String loadConvert (char[] in, int off, int len, char[] convtBuf) {
 619         if (convtBuf.length < len) {
 620             int newLen = len * 2;
 621             if (newLen < 0) {
 622                 newLen = Integer.MAX_VALUE;
 623             }
 624             convtBuf = new char[newLen];
 625         }
 626         char aChar;
 627         char[] out = convtBuf;
 628         int outLen = 0;
 629         int end = off + len;
 630 
 631         while (off < end) {
 632             aChar = in[off++];
 633             if (aChar == '\\') {
 634                 // No need to bounds check since LineReader::readLine excludes
 635                 // unescaped \s at the end of the line
 636                 aChar = in[off++];
 637                 if(aChar == 'u') {
 638                     // Read the xxxx
 639                     if (off > end - 4)
 640                         throw new IllegalArgumentException(
 641                                      "Malformed \\uxxxx encoding.");
 642                     int value = 0;
 643                     for (int i = 0; i < 4; i++) {
 644                         aChar = in[off++];
 645                         switch (aChar) {
 646                           case '0': case '1': case '2': case '3': case '4':
 647                           case '5': case '6': case '7': case '8': case '9':
 648                              value = (value << 4) + aChar - '0';
 649                              break;
 650                           case 'a': case 'b': case 'c':
 651                           case 'd': case 'e': case 'f':
 652                              value = (value << 4) + 10 + aChar - 'a';
 653                              break;
 654                           case 'A': case 'B': case 'C':
 655                           case 'D': case 'E': case 'F':
 656                              value = (value << 4) + 10 + aChar - 'A';
 657                              break;
 658                           default:
 659                               throw new IllegalArgumentException(
 660                                            "Malformed \\uxxxx encoding.");
 661                         }
 662                      }
 663                     out[outLen++] = (char)value;
 664                 } else {
 665                     if (aChar == 't') aChar = '\t';
 666                     else if (aChar == 'r') aChar = '\r';
 667                     else if (aChar == 'n') aChar = '\n';
 668                     else if (aChar == 'f') aChar = '\f';
 669                     out[outLen++] = aChar;
 670                 }
 671             } else {
 672                 out[outLen++] = aChar;
 673             }
 674         }
 675         return new String (out, 0, outLen);
 676     }
 677 
 678     /*
 679      * Converts unicodes to encoded \uxxxx and escapes
 680      * special characters with a preceding slash
 681      */
 682     private String saveConvert(String theString,
 683                                boolean escapeSpace,
 684                                boolean escapeUnicode) {
 685         int len = theString.length();
 686         int bufLen = len * 2;
 687         if (bufLen < 0) {
 688             bufLen = Integer.MAX_VALUE;
 689         }
 690         StringBuilder outBuffer = new StringBuilder(bufLen);
 691 
 692         for(int x=0; x<len; x++) {
 693             char aChar = theString.charAt(x);
 694             // Handle common case first, selecting largest block that
 695             // avoids the specials below
 696             if ((aChar > 61) && (aChar < 127)) {
 697                 if (aChar == '\\') {
 698                     outBuffer.append('\\'); outBuffer.append('\\');
 699                     continue;
 700                 }
 701                 outBuffer.append(aChar);
 702                 continue;
 703             }
 704             switch(aChar) {
 705                 case ' ':
 706                     if (x == 0 || escapeSpace)
 707                         outBuffer.append('\\');
 708                     outBuffer.append(' ');
 709                     break;
 710                 case '\t':outBuffer.append('\\'); outBuffer.append('t');
 711                           break;
 712                 case '\n':outBuffer.append('\\'); outBuffer.append('n');
 713                           break;
 714                 case '\r':outBuffer.append('\\'); outBuffer.append('r');
 715                           break;
 716                 case '\f':outBuffer.append('\\'); outBuffer.append('f');
 717                           break;
 718                 case '=': // Fall through
 719                 case ':': // Fall through
 720                 case '#': // Fall through
 721                 case '!':
 722                     outBuffer.append('\\'); outBuffer.append(aChar);
 723                     break;
 724                 default:
 725                     if (((aChar < 0x0020) || (aChar > 0x007e)) & escapeUnicode ) {
 726                         outBuffer.append('\\');
 727                         outBuffer.append('u');
 728                         outBuffer.append(toHex((aChar >> 12) & 0xF));
 729                         outBuffer.append(toHex((aChar >>  8) & 0xF));
 730                         outBuffer.append(toHex((aChar >>  4) & 0xF));
 731                         outBuffer.append(toHex( aChar        & 0xF));
 732                     } else {
 733                         outBuffer.append(aChar);
 734                     }
 735             }
 736         }
 737         return outBuffer.toString();
 738     }
 739 
 740     private static void writeComments(BufferedWriter bw, String comments)
 741         throws IOException {
 742         bw.write("#");
 743         int len = comments.length();
 744         int current = 0;
 745         int last = 0;
 746         char[] uu = new char[6];
 747         uu[0] = '\\';
 748         uu[1] = 'u';
 749         while (current < len) {
 750             char c = comments.charAt(current);
 751             if (c > '\u00ff' || c == '\n' || c == '\r') {
 752                 if (last != current)
 753                     bw.write(comments.substring(last, current));
 754                 if (c > '\u00ff') {
 755                     uu[2] = toHex((c >> 12) & 0xf);
 756                     uu[3] = toHex((c >>  8) & 0xf);
 757                     uu[4] = toHex((c >>  4) & 0xf);
 758                     uu[5] = toHex( c        & 0xf);
 759                     bw.write(new String(uu));
 760                 } else {
 761                     bw.newLine();
 762                     if (c == '\r' &&
 763                         current != len - 1 &&
 764                         comments.charAt(current + 1) == '\n') {
 765                         current++;
 766                     }
 767                     if (current == len - 1 ||
 768                         (comments.charAt(current + 1) != '#' &&
 769                         comments.charAt(current + 1) != '!'))
 770                         bw.write("#");
 771                 }
 772                 last = current + 1;
 773             }
 774             current++;
 775         }
 776         if (last != current)
 777             bw.write(comments.substring(last, current));
 778         bw.newLine();
 779     }
 780 
 781     /**
 782      * Calls the {@code store(OutputStream out, String comments)} method
 783      * and suppresses IOExceptions that were thrown.
 784      *
 785      * @deprecated This method does not throw an IOException if an I/O error
 786      * occurs while saving the property list.  The preferred way to save a
 787      * properties list is via the {@code store(OutputStream out,
 788      * String comments)} method or the
 789      * {@code storeToXML(OutputStream os, String comment)} method.
 790      *
 791      * @param   out      an output stream.
 792      * @param   comments   a description of the property list.
 793      * @exception  ClassCastException  if this {@code Properties} object
 794      *             contains any keys or values that are not
 795      *             {@code Strings}.
 796      */
 797     @Deprecated
 798     public void save(OutputStream out, String comments)  {
 799         try {
 800             store(out, comments);
 801         } catch (IOException e) {
 802         }
 803     }
 804 
 805     /**
 806      * Writes this property list (key and element pairs) in this
 807      * {@code Properties} table to the output character stream in a
 808      * format suitable for using the {@link #load(java.io.Reader) load(Reader)}
 809      * method.
 810      * <p>
 811      * Properties from the defaults table of this {@code Properties}
 812      * table (if any) are <i>not</i> written out by this method.
 813      * <p>
 814      * If the comments argument is not null, then an ASCII {@code #}
 815      * character, the comments string, and a line separator are first written
 816      * to the output stream. Thus, the {@code comments} can serve as an
 817      * identifying comment. Any one of a line feed ('\n'), a carriage
 818      * return ('\r'), or a carriage return followed immediately by a line feed
 819      * in comments is replaced by a line separator generated by the {@code Writer}
 820      * and if the next character in comments is not character {@code #} or
 821      * character {@code !} then an ASCII {@code #} is written out
 822      * after that line separator.
 823      * <p>
 824      * Next, a comment line is always written, consisting of an ASCII
 825      * {@code #} character, the current date and time (as if produced
 826      * by the {@code toString} method of {@code Date} for the
 827      * current time), and a line separator as generated by the {@code Writer}.
 828      * <p>
 829      * Then every entry in this {@code Properties} table is
 830      * written out, one per line. For each entry the key string is
 831      * written, then an ASCII {@code =}, then the associated
 832      * element string. For the key, all space characters are
 833      * written with a preceding {@code \} character.  For the
 834      * element, leading space characters, but not embedded or trailing
 835      * space characters, are written with a preceding {@code \}
 836      * character. The key and element characters {@code #},
 837      * {@code !}, {@code =}, and {@code :} are written
 838      * with a preceding backslash to ensure that they are properly loaded.
 839      * <p>
 840      * After the entries have been written, the output stream is flushed.
 841      * The output stream remains open after this method returns.
 842      *
 843      * @param   writer      an output character stream writer.
 844      * @param   comments   a description of the property list.
 845      * @exception  IOException if writing this property list to the specified
 846      *             output stream throws an {@code IOException}.
 847      * @exception  ClassCastException  if this {@code Properties} object
 848      *             contains any keys or values that are not {@code Strings}.
 849      * @exception  NullPointerException  if {@code writer} is null.
 850      * @since 1.6
 851      */
 852     public void store(Writer writer, String comments)
 853         throws IOException
 854     {
 855         store0((writer instanceof BufferedWriter)?(BufferedWriter)writer
 856                                                  : new BufferedWriter(writer),
 857                comments,
 858                false);
 859     }
 860 
 861     /**
 862      * Writes this property list (key and element pairs) in this
 863      * {@code Properties} table to the output stream in a format suitable
 864      * for loading into a {@code Properties} table using the
 865      * {@link #load(InputStream) load(InputStream)} method.
 866      * <p>
 867      * Properties from the defaults table of this {@code Properties}
 868      * table (if any) are <i>not</i> written out by this method.
 869      * <p>
 870      * This method outputs the comments, properties keys and values in
 871      * the same format as specified in
 872      * {@link #store(java.io.Writer, java.lang.String) store(Writer)},
 873      * with the following differences:
 874      * <ul>
 875      * <li>The stream is written using the ISO 8859-1 character encoding.
 876      *
 877      * <li>Characters not in Latin-1 in the comments are written as
 878      * {@code \u005Cu}<i>xxxx</i> for their appropriate unicode
 879      * hexadecimal value <i>xxxx</i>.
 880      *
 881      * <li>Characters less than {@code \u005Cu0020} and characters greater
 882      * than {@code \u005Cu007E} in property keys or values are written
 883      * as {@code \u005Cu}<i>xxxx</i> for the appropriate hexadecimal
 884      * value <i>xxxx</i>.
 885      * </ul>
 886      * <p>
 887      * After the entries have been written, the output stream is flushed.
 888      * The output stream remains open after this method returns.
 889      *
 890      * @param   out      an output stream.
 891      * @param   comments   a description of the property list.
 892      * @exception  IOException if writing this property list to the specified
 893      *             output stream throws an {@code IOException}.
 894      * @exception  ClassCastException  if this {@code Properties} object
 895      *             contains any keys or values that are not {@code Strings}.
 896      * @exception  NullPointerException  if {@code out} is null.
 897      * @since 1.2
 898      */
 899     public void store(OutputStream out, String comments)
 900         throws IOException
 901     {
 902         store0(new BufferedWriter(new OutputStreamWriter(out, "8859_1")),
 903                comments,
 904                true);
 905     }
 906 
 907     private void store0(BufferedWriter bw, String comments, boolean escUnicode)
 908         throws IOException
 909     {
 910         if (comments != null) {
 911             writeComments(bw, comments);
 912         }
 913         bw.write("#" + new Date().toString());
 914         bw.newLine();
 915         synchronized (this) {
 916             for (Map.Entry<Object, Object> e : entrySet()) {
 917                 String key = (String)e.getKey();
 918                 String val = (String)e.getValue();
 919                 key = saveConvert(key, true, escUnicode);
 920                 /* No need to escape embedded and trailing spaces for value, hence
 921                  * pass false to flag.
 922                  */
 923                 val = saveConvert(val, false, escUnicode);
 924                 bw.write(key + "=" + val);
 925                 bw.newLine();
 926             }
 927         }
 928         bw.flush();
 929     }
 930 
 931     /**
 932      * Loads all of the properties represented by the XML document on the
 933      * specified input stream into this properties table.
 934      *
 935      * <p>The XML document must have the following DOCTYPE declaration:
 936      * <pre>
 937      * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;
 938      * </pre>
 939      * Furthermore, the document must satisfy the properties DTD described
 940      * above.
 941      *
 942      * <p> An implementation is required to read XML documents that use the
 943      * "{@code UTF-8}" or "{@code UTF-16}" encoding. An implementation may
 944      * support additional encodings.
 945      *
 946      * <p>The specified stream is closed after this method returns.
 947      *
 948      * @param in the input stream from which to read the XML document.
 949      * @throws IOException if reading from the specified input stream
 950      *         results in an {@code IOException}.
 951      * @throws java.io.UnsupportedEncodingException if the document's encoding
 952      *         declaration can be read and it specifies an encoding that is not
 953      *         supported
 954      * @throws InvalidPropertiesFormatException Data on input stream does not
 955      *         constitute a valid XML document with the mandated document type.
 956      * @throws NullPointerException if {@code in} is null.
 957      * @see    #storeToXML(OutputStream, String, String)
 958      * @see    <a href="http://www.w3.org/TR/REC-xml/#charencoding">Character
 959      *         Encoding in Entities</a>
 960      * @since 1.5
 961      */
 962     public synchronized void loadFromXML(InputStream in)
 963         throws IOException, InvalidPropertiesFormatException
 964     {
 965         Objects.requireNonNull(in);
 966         PropertiesDefaultHandler handler = new PropertiesDefaultHandler();
 967         handler.load(this, in);
 968         in.close();
 969     }
 970 
 971     /**
 972      * Emits an XML document representing all of the properties contained
 973      * in this table.
 974      *
 975      * <p> An invocation of this method of the form {@code props.storeToXML(os,
 976      * comment)} behaves in exactly the same way as the invocation
 977      * {@code props.storeToXML(os, comment, "UTF-8");}.
 978      *
 979      * @param os the output stream on which to emit the XML document.
 980      * @param comment a description of the property list, or {@code null}
 981      *        if no comment is desired.
 982      * @throws IOException if writing to the specified output stream
 983      *         results in an {@code IOException}.
 984      * @throws NullPointerException if {@code os} is null.
 985      * @throws ClassCastException  if this {@code Properties} object
 986      *         contains any keys or values that are not
 987      *         {@code Strings}.
 988      * @see    #loadFromXML(InputStream)
 989      * @since 1.5
 990      */
 991     public void storeToXML(OutputStream os, String comment)
 992         throws IOException
 993     {
 994         storeToXML(os, comment, "UTF-8");
 995     }
 996 
 997     /**
 998      * Emits an XML document representing all of the properties contained
 999      * in this table, using the specified encoding.
1000      *
1001      * <p>The XML document will have the following DOCTYPE declaration:
1002      * <pre>
1003      * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;
1004      * </pre>
1005      *
1006      * <p>If the specified comment is {@code null} then no comment
1007      * will be stored in the document.
1008      *
1009      * <p> An implementation is required to support writing of XML documents
1010      * that use the "{@code UTF-8}" or "{@code UTF-16}" encoding. An
1011      * implementation may support additional encodings.
1012      *
1013      * <p>The specified stream remains open after this method returns.
1014      *
1015      * <p>This method behaves the same as
1016      * {@linkplain #storeToXML(OutputStream os, String comment, Charset charset)}
1017      * except that it will {@linkplain java.nio.charset.Charset#forName look up the charset}
1018      * using the given encoding name.
1019      *
1020      * @param os        the output stream on which to emit the XML document.
1021      * @param comment   a description of the property list, or {@code null}
1022      *                  if no comment is desired.
1023      * @param  encoding the name of a supported
1024      *                  <a href="../lang/package-summary.html#charenc">
1025      *                  character encoding</a>
1026      *
1027      * @throws IOException if writing to the specified output stream
1028      *         results in an {@code IOException}.
1029      * @throws java.io.UnsupportedEncodingException if the encoding is not
1030      *         supported by the implementation.
1031      * @throws NullPointerException if {@code os} is {@code null},
1032      *         or if {@code encoding} is {@code null}.
1033      * @throws ClassCastException  if this {@code Properties} object
1034      *         contains any keys or values that are not {@code Strings}.
1035      * @see    #loadFromXML(InputStream)
1036      * @see    <a href="http://www.w3.org/TR/REC-xml/#charencoding">Character
1037      *         Encoding in Entities</a>
1038      * @since 1.5
1039      */
1040     public void storeToXML(OutputStream os, String comment, String encoding)
1041         throws IOException {
1042         Objects.requireNonNull(os);
1043         Objects.requireNonNull(encoding);
1044 
1045         try {
1046             Charset charset = Charset.forName(encoding);
1047             storeToXML(os, comment, charset);
1048         } catch (IllegalCharsetNameException | UnsupportedCharsetException e) {
1049             throw new UnsupportedEncodingException(encoding);
1050         }
1051     }
1052 
1053     /**
1054      * Emits an XML document representing all of the properties contained
1055      * in this table, using the specified encoding.
1056      *
1057      * <p>The XML document will have the following DOCTYPE declaration:
1058      * <pre>
1059      * &lt;!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"&gt;
1060      * </pre>
1061      *
1062      * <p>If the specified comment is {@code null} then no comment
1063      * will be stored in the document.
1064      *
1065      * <p> An implementation is required to support writing of XML documents
1066      * that use the "{@code UTF-8}" or "{@code UTF-16}" encoding. An
1067      * implementation may support additional encodings.
1068      *
1069      * <p> Unmappable characters for the specified charset will be encoded as
1070      * numeric character references.
1071      *
1072      * <p>The specified stream remains open after this method returns.
1073      *
1074      * @param os        the output stream on which to emit the XML document.
1075      * @param comment   a description of the property list, or {@code null}
1076      *                  if no comment is desired.
1077      * @param charset   the charset
1078      *
1079      * @throws IOException if writing to the specified output stream
1080      *         results in an {@code IOException}.
1081      * @throws NullPointerException if {@code os} or {@code charset} is {@code null}.
1082      * @throws ClassCastException  if this {@code Properties} object
1083      *         contains any keys or values that are not {@code Strings}.
1084      * @see    #loadFromXML(InputStream)
1085      * @see    <a href="http://www.w3.org/TR/REC-xml/#charencoding">Character
1086      *         Encoding in Entities</a>
1087      * @since 10
1088      */
1089     public void storeToXML(OutputStream os, String comment, Charset charset)
1090         throws IOException {
1091         Objects.requireNonNull(os, "OutputStream");
1092         Objects.requireNonNull(charset, "Charset");
1093         PropertiesDefaultHandler handler = new PropertiesDefaultHandler();
1094         handler.store(this, os, comment, charset);
1095     }
1096 
1097     /**
1098      * Searches for the property with the specified key in this property list.
1099      * If the key is not found in this property list, the default property list,
1100      * and its defaults, recursively, are then checked. The method returns
1101      * {@code null} if the property is not found.
1102      *
1103      * @param   key   the property key.
1104      * @return  the value in this property list with the specified key value.
1105      * @see     #setProperty
1106      * @see     #defaults
1107      */
1108     public String getProperty(String key) {
1109         Object oval = map.get(key);
1110         String sval = (oval instanceof String) ? (String)oval : null;
1111         Properties defaults;
1112         return ((sval == null) && ((defaults = this.defaults) != null)) ? defaults.getProperty(key) : sval;
1113     }
1114 
1115     /**
1116      * Searches for the property with the specified key in this property list.
1117      * If the key is not found in this property list, the default property list,
1118      * and its defaults, recursively, are then checked. The method returns the
1119      * default value argument if the property is not found.
1120      *
1121      * @param   key            the hashtable key.
1122      * @param   defaultValue   a default value.
1123      *
1124      * @return  the value in this property list with the specified key value.
1125      * @see     #setProperty
1126      * @see     #defaults
1127      */
1128     public String getProperty(String key, String defaultValue) {
1129         String val = getProperty(key);
1130         return (val == null) ? defaultValue : val;
1131     }
1132 
1133     /**
1134      * Returns an enumeration of all the keys in this property list,
1135      * including distinct keys in the default property list if a key
1136      * of the same name has not already been found from the main
1137      * properties list.
1138      *
1139      * @return  an enumeration of all the keys in this property list, including
1140      *          the keys in the default property list.
1141      * @throws  ClassCastException if any key in this property list
1142      *          is not a string.
1143      * @see     java.util.Enumeration
1144      * @see     java.util.Properties#defaults
1145      * @see     #stringPropertyNames
1146      */
1147     public Enumeration<?> propertyNames() {
1148         Hashtable<String,Object> h = new Hashtable<>();
1149         enumerate(h);
1150         return h.keys();
1151     }
1152 
1153     /**
1154      * Returns an unmodifiable set of keys from this property list
1155      * where the key and its corresponding value are strings,
1156      * including distinct keys in the default property list if a key
1157      * of the same name has not already been found from the main
1158      * properties list.  Properties whose key or value is not
1159      * of type {@code String} are omitted.
1160      * <p>
1161      * The returned set is not backed by this {@code Properties} object.
1162      * Changes to this {@code Properties} object are not reflected in the
1163      * returned set.
1164      *
1165      * @return  an unmodifiable set of keys in this property list where
1166      *          the key and its corresponding value are strings,
1167      *          including the keys in the default property list.
1168      * @see     java.util.Properties#defaults
1169      * @since   1.6
1170      */
1171     public Set<String> stringPropertyNames() {
1172         Map<String, String> h = new HashMap<>();
1173         enumerateStringProperties(h);
1174         return Collections.unmodifiableSet(h.keySet());
1175     }
1176 
1177     /**
1178      * Prints this property list out to the specified output stream.
1179      * This method is useful for debugging.
1180      *
1181      * @param   out   an output stream.
1182      * @throws  ClassCastException if any key in this property list
1183      *          is not a string.
1184      */
1185     public void list(PrintStream out) {
1186         out.println("-- listing properties --");
1187         Map<String, Object> h = new HashMap<>();
1188         enumerate(h);
1189         for (Map.Entry<String, Object> e : h.entrySet()) {
1190             String key = e.getKey();
1191             String val = (String)e.getValue();
1192             if (val.length() > 40) {
1193                 val = val.substring(0, 37) + "...";
1194             }
1195             out.println(key + "=" + val);
1196         }
1197     }
1198 
1199     /**
1200      * Prints this property list out to the specified output stream.
1201      * This method is useful for debugging.
1202      *
1203      * @param   out   an output stream.
1204      * @throws  ClassCastException if any key in this property list
1205      *          is not a string.
1206      * @since   1.1
1207      */
1208     /*
1209      * Rather than use an anonymous inner class to share common code, this
1210      * method is duplicated in order to ensure that a non-1.1 compiler can
1211      * compile this file.
1212      */
1213     public void list(PrintWriter out) {
1214         out.println("-- listing properties --");
1215         Map<String, Object> h = new HashMap<>();
1216         enumerate(h);
1217         for (Map.Entry<String, Object> e : h.entrySet()) {
1218             String key = e.getKey();
1219             String val = (String)e.getValue();
1220             if (val.length() > 40) {
1221                 val = val.substring(0, 37) + "...";
1222             }
1223             out.println(key + "=" + val);
1224         }
1225     }
1226 
1227     /**
1228      * Enumerates all key/value pairs into the specified Map.
1229      * @param h the Map
1230      * @throws ClassCastException if any of the property keys
1231      *         is not of String type.
1232      */
1233     private void enumerate(Map<String, Object> h) {
1234         if (defaults != null) {
1235             defaults.enumerate(h);
1236         }
1237         for (Map.Entry<Object, Object> e : entrySet()) {
1238             String key = (String)e.getKey();
1239             h.put(key, e.getValue());
1240         }
1241     }
1242 
1243     /**
1244      * Enumerates all key/value pairs into the specified Map
1245      * and omits the property if the key or value is not a string.
1246      * @param h the Map
1247      */
1248     private void enumerateStringProperties(Map<String, String> h) {
1249         if (defaults != null) {
1250             defaults.enumerateStringProperties(h);
1251         }
1252         for (Map.Entry<Object, Object> e : entrySet()) {
1253             Object k = e.getKey();
1254             Object v = e.getValue();
1255             if (k instanceof String && v instanceof String) {
1256                 h.put((String) k, (String) v);
1257             }
1258         }
1259     }
1260 
1261     /**
1262      * Convert a nibble to a hex character
1263      * @param   nibble  the nibble to convert.
1264      */
1265     private static char toHex(int nibble) {
1266         return hexDigit[(nibble & 0xF)];
1267     }
1268 
1269     /** A table of hex digits */
1270     private static final char[] hexDigit = {
1271         '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'
1272     };
1273 
1274     //
1275     // Hashtable methods overridden and delegated to a ConcurrentHashMap instance
1276 
1277     @Override
1278     public int size() {
1279         return map.size();
1280     }
1281 
1282     @Override
1283     public boolean isEmpty() {
1284         return map.isEmpty();
1285     }
1286 
1287     @Override
1288     public Enumeration<Object> keys() {
1289         // CHM.keys() returns Iterator w/ remove() - instead wrap keySet()
1290         return Collections.enumeration(map.keySet());
1291     }
1292 
1293     @Override
1294     public Enumeration<Object> elements() {
1295         // CHM.elements() returns Iterator w/ remove() - instead wrap values()
1296         return Collections.enumeration(map.values());
1297     }
1298 
1299     @Override
1300     public boolean contains(Object value) {
1301         return map.contains(value);
1302     }
1303 
1304     @Override
1305     public boolean containsValue(Object value) {
1306         return map.containsValue(value);
1307     }
1308 
1309     @Override
1310     public boolean containsKey(Object key) {
1311         return map.containsKey(key);
1312     }
1313 
1314     @Override
1315     public Object get(Object key) {
1316         return map.get(key);
1317     }
1318 
1319     @Override
1320     public synchronized Object put(Object key, Object value) {
1321         return map.put(key, value);
1322     }
1323 
1324     @Override
1325     public synchronized Object remove(Object key) {
1326         return map.remove(key);
1327     }
1328 
1329     @Override
1330     public synchronized void putAll(Map<?, ?> t) {
1331         map.putAll(t);
1332     }
1333 
1334     @Override
1335     public synchronized void clear() {
1336         map.clear();
1337     }
1338 
1339     @Override
1340     public synchronized String toString() {
1341         return map.toString();
1342     }
1343 
1344     @Override
1345     public Set<Object> keySet() {
1346         return Collections.synchronizedSet(map.keySet(), this);
1347     }
1348 
1349     @Override
1350     public Collection<Object> values() {
1351         return Collections.synchronizedCollection(map.values(), this);
1352     }
1353 
1354     @Override
1355     public Set<Map.Entry<Object, Object>> entrySet() {
1356         return Collections.synchronizedSet(new EntrySet(map.entrySet()), this);
1357     }
1358 
1359     /*
1360      * Properties.entrySet() should not support add/addAll, however
1361      * ConcurrentHashMap.entrySet() provides add/addAll.  This class wraps the
1362      * Set returned from CHM, changing add/addAll to throw UOE.
1363      */
1364     private static class EntrySet implements Set<Map.Entry<Object, Object>> {
1365         private Set<Map.Entry<Object,Object>> entrySet;
1366 
1367         private EntrySet(Set<Map.Entry<Object, Object>> entrySet) {
1368             this.entrySet = entrySet;
1369         }
1370 
1371         @Override public int size() { return entrySet.size(); }
1372         @Override public boolean isEmpty() { return entrySet.isEmpty(); }
1373         @Override public boolean contains(Object o) { return entrySet.contains(o); }
1374         @Override public Object[] toArray() { return entrySet.toArray(); }
1375         @Override public <T> T[] toArray(T[] a) { return entrySet.toArray(a); }
1376         @Override public void clear() { entrySet.clear(); }
1377         @Override public boolean remove(Object o) { return entrySet.remove(o); }
1378 
1379         @Override
1380         public boolean add(Map.Entry<Object, Object> e) {
1381             throw new UnsupportedOperationException();
1382         }
1383 
1384         @Override
1385         public boolean addAll(Collection<? extends Map.Entry<Object, Object>> c) {
1386             throw new UnsupportedOperationException();
1387         }
1388 
1389         @Override
1390         public boolean containsAll(Collection<?> c) {
1391             return entrySet.containsAll(c);
1392         }
1393 
1394         @Override
1395         public boolean removeAll(Collection<?> c) {
1396             return entrySet.removeAll(c);
1397         }
1398 
1399         @Override
1400         public boolean retainAll(Collection<?> c) {
1401             return entrySet.retainAll(c);
1402         }
1403 
1404         @Override
1405         public Iterator<Map.Entry<Object, Object>> iterator() {
1406             return entrySet.iterator();
1407         }
1408     }
1409 
1410     @Override
1411     public synchronized boolean equals(Object o) {
1412         return map.equals(o);
1413     }
1414 
1415     @Override
1416     public synchronized int hashCode() {
1417         return map.hashCode();
1418     }
1419 
1420     @Override
1421     public Object getOrDefault(Object key, Object defaultValue) {
1422         return map.getOrDefault(key, defaultValue);
1423     }
1424 
1425     @Override
1426     public synchronized void forEach(BiConsumer<? super Object, ? super Object> action) {
1427         map.forEach(action);
1428     }
1429 
1430     @Override
1431     public synchronized void replaceAll(BiFunction<? super Object, ? super Object, ?> function) {
1432         map.replaceAll(function);
1433     }
1434 
1435     @Override
1436     public synchronized Object putIfAbsent(Object key, Object value) {
1437         return map.putIfAbsent(key, value);
1438     }
1439 
1440     @Override
1441     public synchronized boolean remove(Object key, Object value) {
1442         return map.remove(key, value);
1443     }
1444 
1445     @Override
1446     public synchronized boolean replace(Object key, Object oldValue, Object newValue) {
1447         return map.replace(key, oldValue, newValue);
1448     }
1449 
1450     @Override
1451     public synchronized Object replace(Object key, Object value) {
1452         return map.replace(key, value);
1453     }
1454 
1455     @Override
1456     public synchronized Object computeIfAbsent(Object key,
1457             Function<? super Object, ?> mappingFunction) {
1458         return map.computeIfAbsent(key, mappingFunction);
1459     }
1460 
1461     @Override
1462     public synchronized Object computeIfPresent(Object key,
1463             BiFunction<? super Object, ? super Object, ?> remappingFunction) {
1464         return map.computeIfPresent(key, remappingFunction);
1465     }
1466 
1467     @Override
1468     public synchronized Object compute(Object key,
1469             BiFunction<? super Object, ? super Object, ?> remappingFunction) {
1470         return map.compute(key, remappingFunction);
1471     }
1472 
1473     @Override
1474     public synchronized Object merge(Object key, Object value,
1475             BiFunction<? super Object, ? super Object, ?> remappingFunction) {
1476         return map.merge(key, value, remappingFunction);
1477     }
1478 
1479     //
1480     // Special Hashtable methods
1481 
1482     @Override
1483     protected void rehash() { /* no-op */ }
1484 
1485     @Override
1486     public synchronized Object clone() {
1487         Properties clone = (Properties) cloneHashtable();
1488         clone.map = new ConcurrentHashMap<>(map);
1489         return clone;
1490     }
1491 
1492     //
1493     // Hashtable serialization overrides
1494     // (these should emit and consume Hashtable-compatible stream)
1495 
1496     @Override
1497     void writeHashtable(ObjectOutputStream s) throws IOException {
1498         var map = this.map;
1499         List<Object> entryStack = new ArrayList<>(map.size() * 2); // an estimate
1500 
1501         for (Map.Entry<Object, Object> entry : map.entrySet()) {
1502             entryStack.add(entry.getValue());
1503             entryStack.add(entry.getKey());
1504         }
1505 
1506         // Write out the simulated threshold, loadfactor
1507         float loadFactor = 0.75f;
1508         int count = entryStack.size() / 2;
1509         int length = (int)(count / loadFactor) + (count / 20) + 3;
1510         if (length > count && (length & 1) == 0) {
1511             length--;
1512         }
1513         synchronized (map) { // in case of multiple concurrent serializations
1514             defaultWriteHashtable(s, length, loadFactor);
1515         }
1516 
1517         // Write out simulated length and real count of elements
1518         s.writeInt(length);
1519         s.writeInt(count);
1520 
1521         // Write out the key/value objects from the stacked entries
1522         for (int i = entryStack.size() - 1; i >= 0; i--) {
1523             s.writeObject(entryStack.get(i));
1524         }
1525     }
1526 
1527     @Override
1528     void readHashtable(ObjectInputStream s) throws IOException,
1529             ClassNotFoundException {
1530         // Read in the threshold and loadfactor
1531         s.defaultReadObject();
1532 
1533         // Read the original length of the array and number of elements
1534         int origlength = s.readInt();
1535         int elements = s.readInt();
1536 
1537         // Validate # of elements
1538         if (elements < 0) {
1539             throw new StreamCorruptedException("Illegal # of Elements: " + elements);
1540         }
1541 
1542         // Constructing the backing map will lazily create an array when the first element is
1543         // added, so check it before construction. Note that CHM's constructor takes a size
1544         // that is the number of elements to be stored -- not the table size -- so it must be
1545         // inflated by the default load factor of 0.75, then inflated to the next power of two.
1546         // (CHM uses the same power-of-two computation as HashMap, and HashMap.tableSizeFor is
1547         // accessible here.) Check Map.Entry[].class since it's the nearest public type to
1548         // what is actually created.
1549         SharedSecrets.getJavaObjectInputStreamAccess()
1550                      .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor((int)(elements / 0.75)));
1551 
1552         // create CHM of appropriate capacity
1553         var map = new ConcurrentHashMap<>(elements);
1554 
1555         // Read all the key/value objects
1556         for (; elements > 0; elements--) {
1557             Object key = s.readObject();
1558             Object value = s.readObject();
1559             map.put(key, value);
1560         }
1561         this.map = map;
1562     }
1563 }