1 /*
   2  * Copyright (c) 2000, 2013, 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.nio.charset;
  27 
  28 import java.nio.ByteBuffer;
  29 import java.nio.CharBuffer;
  30 import java.nio.charset.spi.CharsetProvider;
  31 import java.security.AccessController;
  32 import java.security.PrivilegedAction;
  33 import java.util.Arrays;
  34 import java.util.Collections;
  35 import java.util.HashSet;
  36 import java.util.Iterator;
  37 import java.util.Locale;
  38 import java.util.Map;
  39 import java.util.NoSuchElementException;
  40 import java.util.Set;
  41 import java.util.ServiceLoader;
  42 import java.util.ServiceConfigurationError;
  43 import java.util.SortedMap;
  44 import java.util.TreeMap;
  45 import sun.misc.ASCIICaseInsensitiveComparator;
  46 import sun.nio.cs.StandardCharsets;
  47 import sun.nio.cs.ThreadLocalCoders;
  48 import sun.security.action.GetPropertyAction;
  49 
  50 
  51 /**
  52  * A named mapping between sequences of sixteen-bit Unicode <a
  53  * href="../../lang/Character.html#unicode">code units</a> and sequences of
  54  * bytes.  This class defines methods for creating decoders and encoders and
  55  * for retrieving the various names associated with a charset.  Instances of
  56  * this class are immutable.
  57  *
  58  * <p> This class also defines static methods for testing whether a particular
  59  * charset is supported, for locating charset instances by name, and for
  60  * constructing a map that contains every charset for which support is
  61  * available in the current Java virtual machine.  Support for new charsets can
  62  * be added via the service-provider interface defined in the {@link
  63  * java.nio.charset.spi.CharsetProvider} class.
  64  *
  65  * <p> All of the methods defined in this class are safe for use by multiple
  66  * concurrent threads.
  67  *
  68  *
  69  * <a name="names"></a><a name="charenc"></a>
  70  * <h2>Charset names</h2>
  71  *
  72  * <p> Charsets are named by strings composed of the following characters:
  73  *
  74  * <ul>
  75  *
  76  *   <li> The uppercase letters <tt>'A'</tt> through <tt>'Z'</tt>
  77  *        (<tt>'&#92;u0041'</tt>&nbsp;through&nbsp;<tt>'&#92;u005a'</tt>),
  78  *
  79  *   <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt>
  80  *        (<tt>'&#92;u0061'</tt>&nbsp;through&nbsp;<tt>'&#92;u007a'</tt>),
  81  *
  82  *   <li> The digits <tt>'0'</tt> through <tt>'9'</tt>
  83  *        (<tt>'&#92;u0030'</tt>&nbsp;through&nbsp;<tt>'&#92;u0039'</tt>),
  84  *
  85  *   <li> The dash character <tt>'-'</tt>
  86  *        (<tt>'&#92;u002d'</tt>,&nbsp;<small>HYPHEN-MINUS</small>),
  87  *
  88  *   <li> The plus character <tt>'+'</tt>
  89  *        (<tt>'&#92;u002b'</tt>,&nbsp;<small>PLUS SIGN</small>),
  90  *
  91  *   <li> The period character <tt>'.'</tt>
  92  *        (<tt>'&#92;u002e'</tt>,&nbsp;<small>FULL STOP</small>),
  93  *
  94  *   <li> The colon character <tt>':'</tt>
  95  *        (<tt>'&#92;u003a'</tt>,&nbsp;<small>COLON</small>), and
  96  *
  97  *   <li> The underscore character <tt>'_'</tt>
  98  *        (<tt>'&#92;u005f'</tt>,&nbsp;<small>LOW&nbsp;LINE</small>).
  99  *
 100  * </ul>
 101  *
 102  * A charset name must begin with either a letter or a digit.  The empty string
 103  * is not a legal charset name.  Charset names are not case-sensitive; that is,
 104  * case is always ignored when comparing charset names.  Charset names
 105  * generally follow the conventions documented in <a
 106  * href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278:&nbsp;IANA Charset
 107  * Registration Procedures</i></a>.
 108  *
 109  * <p> Every charset has a <i>canonical name</i> and may also have one or more
 110  * <i>aliases</i>.  The canonical name is returned by the {@link #name() name} method
 111  * of this class.  Canonical names are, by convention, usually in upper case.
 112  * The aliases of a charset are returned by the {@link #aliases() aliases}
 113  * method.
 114  *
 115  * <p><a name="hn">Some charsets have an <i>historical name</i> that is defined for
 116  * compatibility with previous versions of the Java platform.</a>  A charset's
 117  * historical name is either its canonical name or one of its aliases.  The
 118  * historical name is returned by the <tt>getEncoding()</tt> methods of the
 119  * {@link java.io.InputStreamReader#getEncoding InputStreamReader} and {@link
 120  * java.io.OutputStreamWriter#getEncoding OutputStreamWriter} classes.
 121  *
 122  * <p><a name="iana"> </a>If a charset listed in the <a
 123  * href="http://www.iana.org/assignments/character-sets"><i>IANA Charset
 124  * Registry</i></a> is supported by an implementation of the Java platform then
 125  * its canonical name must be the name listed in the registry. Many charsets
 126  * are given more than one name in the registry, in which case the registry
 127  * identifies one of the names as <i>MIME-preferred</i>.  If a charset has more
 128  * than one registry name then its canonical name must be the MIME-preferred
 129  * name and the other names in the registry must be valid aliases.  If a
 130  * supported charset is not listed in the IANA registry then its canonical name
 131  * must begin with one of the strings <tt>"X-"</tt> or <tt>"x-"</tt>.
 132  *
 133  * <p> The IANA charset registry does change over time, and so the canonical
 134  * name and the aliases of a particular charset may also change over time.  To
 135  * ensure compatibility it is recommended that no alias ever be removed from a
 136  * charset, and that if the canonical name of a charset is changed then its
 137  * previous canonical name be made into an alias.
 138  *
 139  *
 140  * <h2>Standard charsets</h2>
 141  *
 142  *
 143  *
 144  * <p><a name="standard">Every implementation of the Java platform is required to support the
 145  * following standard charsets.</a>  Consult the release documentation for your
 146  * implementation to see if any other charsets are supported.  The behavior
 147  * of such optional charsets may differ between implementations.
 148  *
 149  * <blockquote><table width="80%" summary="Description of standard charsets">
 150  * <tr><th align="left">Charset</th><th align="left">Description</th></tr>
 151  * <tr><td valign=top><tt>US-ASCII</tt></td>
 152  *     <td>Seven-bit ASCII, a.k.a. <tt>ISO646-US</tt>,
 153  *         a.k.a. the Basic Latin block of the Unicode character set</td></tr>
 154  * <tr><td valign=top><tt>ISO-8859-1&nbsp;&nbsp;</tt></td>
 155  *     <td>ISO Latin Alphabet No. 1, a.k.a. <tt>ISO-LATIN-1</tt></td></tr>
 156  * <tr><td valign=top><tt>UTF-8</tt></td>
 157  *     <td>Eight-bit UCS Transformation Format</td></tr>
 158  * <tr><td valign=top><tt>UTF-16BE</tt></td>
 159  *     <td>Sixteen-bit UCS Transformation Format,
 160  *         big-endian byte&nbsp;order</td></tr>
 161  * <tr><td valign=top><tt>UTF-16LE</tt></td>
 162  *     <td>Sixteen-bit UCS Transformation Format,
 163  *         little-endian byte&nbsp;order</td></tr>
 164  * <tr><td valign=top><tt>UTF-16</tt></td>
 165  *     <td>Sixteen-bit UCS Transformation Format,
 166  *         byte&nbsp;order identified by an optional byte-order mark</td></tr>
 167  * </table></blockquote>
 168  *
 169  * <p> The <tt>UTF-8</tt> charset is specified by <a
 170  * href="http://www.ietf.org/rfc/rfc2279.txt"><i>RFC&nbsp;2279</i></a>; the
 171  * transformation format upon which it is based is specified in
 172  * Amendment&nbsp;2 of ISO&nbsp;10646-1 and is also described in the <a
 173  * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
 174  * Standard</i></a>.
 175  *
 176  * <p> The <tt>UTF-16</tt> charsets are specified by <a
 177  * href="http://www.ietf.org/rfc/rfc2781.txt"><i>RFC&nbsp;2781</i></a>; the
 178  * transformation formats upon which they are based are specified in
 179  * Amendment&nbsp;1 of ISO&nbsp;10646-1 and are also described in the <a
 180  * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
 181  * Standard</i></a>.
 182  *
 183  * <p> The <tt>UTF-16</tt> charsets use sixteen-bit quantities and are
 184  * therefore sensitive to byte order.  In these encodings the byte order of a
 185  * stream may be indicated by an initial <i>byte-order mark</i> represented by
 186  * the Unicode character <tt>'&#92;uFEFF'</tt>.  Byte-order marks are handled
 187  * as follows:
 188  *
 189  * <ul>
 190  *
 191  *   <li><p> When decoding, the <tt>UTF-16BE</tt> and <tt>UTF-16LE</tt>
 192  *   charsets interpret the initial byte-order marks as a <small>ZERO-WIDTH
 193  *   NON-BREAKING SPACE</small>; when encoding, they do not write
 194  *   byte-order marks. </p></li>
 195 
 196  *
 197  *   <li><p> When decoding, the <tt>UTF-16</tt> charset interprets the
 198  *   byte-order mark at the beginning of the input stream to indicate the
 199  *   byte-order of the stream but defaults to big-endian if there is no
 200  *   byte-order mark; when encoding, it uses big-endian byte order and writes
 201  *   a big-endian byte-order mark. </p></li>
 202  *
 203  * </ul>
 204  *
 205  * In any case, byte order marks occurring after the first element of an
 206  * input sequence are not omitted since the same code is used to represent
 207  * <small>ZERO-WIDTH NON-BREAKING SPACE</small>.
 208  *
 209  * <p> Every instance of the Java virtual machine has a default charset, which
 210  * may or may not be one of the standard charsets.  The default charset is
 211  * determined during virtual-machine startup and typically depends upon the
 212  * locale and charset being used by the underlying operating system. </p>
 213  *
 214  * <p>The {@link StandardCharsets} class defines constants for each of the
 215  * standard charsets.
 216  *
 217  * <h2>Terminology</h2>
 218  *
 219  * <p> The name of this class is taken from the terms used in
 220  * <a href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278</i></a>.
 221  * In that document a <i>charset</i> is defined as the combination of
 222  * one or more coded character sets and a character-encoding scheme.
 223  * (This definition is confusing; some other software systems define
 224  * <i>charset</i> as a synonym for <i>coded character set</i>.)
 225  *
 226  * <p> A <i>coded character set</i> is a mapping between a set of abstract
 227  * characters and a set of integers.  US-ASCII, ISO&nbsp;8859-1,
 228  * JIS&nbsp;X&nbsp;0201, and Unicode are examples of coded character sets.
 229  *
 230  * <p> Some standards have defined a <i>character set</i> to be simply a
 231  * set of abstract characters without an associated assigned numbering.
 232  * An alphabet is an example of such a character set.  However, the subtle
 233  * distinction between <i>character set</i> and <i>coded character set</i>
 234  * is rarely used in practice; the former has become a short form for the
 235  * latter, including in the Java API specification.
 236  *
 237  * <p> A <i>character-encoding scheme</i> is a mapping between one or more
 238  * coded character sets and a set of octet (eight-bit byte) sequences.
 239  * UTF-8, UTF-16, ISO&nbsp;2022, and EUC are examples of
 240  * character-encoding schemes.  Encoding schemes are often associated with
 241  * a particular coded character set; UTF-8, for example, is used only to
 242  * encode Unicode.  Some schemes, however, are associated with multiple
 243  * coded character sets; EUC, for example, can be used to encode
 244  * characters in a variety of Asian coded character sets.
 245  *
 246  * <p> When a coded character set is used exclusively with a single
 247  * character-encoding scheme then the corresponding charset is usually
 248  * named for the coded character set; otherwise a charset is usually named
 249  * for the encoding scheme and, possibly, the locale of the coded
 250  * character sets that it supports.  Hence <tt>US-ASCII</tt> is both the
 251  * name of a coded character set and of the charset that encodes it, while
 252  * <tt>EUC-JP</tt> is the name of the charset that encodes the
 253  * JIS&nbsp;X&nbsp;0201, JIS&nbsp;X&nbsp;0208, and JIS&nbsp;X&nbsp;0212
 254  * coded character sets for the Japanese language.
 255  *
 256  * <p> The native character encoding of the Java programming language is
 257  * UTF-16.  A charset in the Java platform therefore defines a mapping
 258  * between sequences of sixteen-bit UTF-16 code units (that is, sequences
 259  * of chars) and sequences of bytes. </p>
 260  *
 261  *
 262  * @author Mark Reinhold
 263  * @author JSR-51 Expert Group
 264  * @since 1.4
 265  *
 266  * @see CharsetDecoder
 267  * @see CharsetEncoder
 268  * @see java.nio.charset.spi.CharsetProvider
 269  * @see java.lang.Character
 270  */
 271 
 272 public abstract class Charset
 273     implements Comparable<Charset>
 274 {
 275 
 276     /* -- Static methods -- */
 277 
 278     private static volatile String bugLevel = null;
 279 
 280     static boolean atBugLevel(String bl) {              // package-private
 281         String level = bugLevel;
 282         if (level == null) {
 283             if (!sun.misc.VM.isBooted())
 284                 return false;
 285             bugLevel = level = AccessController.doPrivileged(
 286                 new GetPropertyAction("sun.nio.cs.bugLevel", ""));
 287         }
 288         return level.equals(bl);
 289     }
 290 
 291     /**
 292      * Checks that the given string is a legal charset name. </p>
 293      *
 294      * @param  s
 295      *         A purported charset name
 296      *
 297      * @throws  IllegalCharsetNameException
 298      *          If the given name is not a legal charset name
 299      */
 300     private static void checkName(String s) {
 301         int n = s.length();
 302         if (!atBugLevel("1.4")) {
 303             if (n == 0)
 304                 throw new IllegalCharsetNameException(s);
 305         }
 306         for (int i = 0; i < n; i++) {
 307             char c = s.charAt(i);
 308             if (c >= 'A' && c <= 'Z') continue;
 309             if (c >= 'a' && c <= 'z') continue;
 310             if (c >= '0' && c <= '9') continue;
 311             if (c == '-' && i != 0) continue;
 312             if (c == '+' && i != 0) continue;
 313             if (c == ':' && i != 0) continue;
 314             if (c == '_' && i != 0) continue;
 315             if (c == '.' && i != 0) continue;
 316             throw new IllegalCharsetNameException(s);
 317         }
 318     }
 319 
 320     /* The standard set of charsets */
 321     private static CharsetProvider standardProvider = new StandardCharsets();
 322 
 323     // Cache of the most-recently-returned charsets,
 324     // along with the names that were used to find them
 325     //
 326     private static volatile Object[] cache1 = null; // "Level 1" cache
 327     private static volatile Object[] cache2 = null; // "Level 2" cache
 328 
 329     private static void cache(String charsetName, Charset cs) {
 330         cache2 = cache1;
 331         cache1 = new Object[] { charsetName, cs };
 332     }
 333 
 334     // Creates an iterator that walks over the available providers, ignoring
 335     // those whose lookup or instantiation causes a security exception to be
 336     // thrown.  Should be invoked with full privileges.
 337     //
 338     private static Iterator<CharsetProvider> providers() {
 339         return new Iterator<>() {
 340                 ClassLoader cl = ClassLoader.getSystemClassLoader();
 341                 ServiceLoader<CharsetProvider> sl =
 342                     ServiceLoader.load(CharsetProvider.class, cl);
 343                 Iterator<CharsetProvider> i = sl.iterator();
 344                 CharsetProvider next = null;
 345 
 346                 private boolean getNext() {
 347                     while (next == null) {
 348                         try {
 349                             if (!i.hasNext())
 350                                 return false;
 351                             next = i.next();
 352                         } catch (ServiceConfigurationError sce) {
 353                             if (sce.getCause() instanceof SecurityException) {
 354                                 // Ignore security exceptions
 355                                 continue;
 356                             }
 357                             throw sce;
 358                         }
 359                     }
 360                     return true;
 361                 }
 362 
 363                 public boolean hasNext() {
 364                     return getNext();
 365                 }
 366 
 367                 public CharsetProvider next() {
 368                     if (!getNext())
 369                         throw new NoSuchElementException();
 370                     CharsetProvider n = next;
 371                     next = null;
 372                     return n;
 373                 }
 374 
 375                 public void remove() {
 376                     throw new UnsupportedOperationException();
 377                 }
 378 
 379             };
 380     }
 381 
 382     // Thread-local gate to prevent recursive provider lookups
 383     private static ThreadLocal<ThreadLocal<?>> gate =
 384             new ThreadLocal<ThreadLocal<?>>();
 385 
 386     private static Charset lookupViaProviders(final String charsetName) {
 387 
 388         // The runtime startup sequence looks up standard charsets as a
 389         // consequence of the VM's invocation of System.initializeSystemClass
 390         // in order to, e.g., set system properties and encode filenames.  At
 391         // that point the application class loader has not been initialized,
 392         // however, so we can't look for providers because doing so will cause
 393         // that loader to be prematurely initialized with incomplete
 394         // information.
 395         //
 396         if (!sun.misc.VM.isBooted())
 397             return null;
 398 
 399         if (gate.get() != null)
 400             // Avoid recursive provider lookups
 401             return null;
 402         try {
 403             gate.set(gate);
 404 
 405             return AccessController.doPrivileged(
 406                 new PrivilegedAction<>() {
 407                     public Charset run() {
 408                         for (Iterator<CharsetProvider> i = providers();
 409                              i.hasNext();) {
 410                             CharsetProvider cp = i.next();
 411                             Charset cs = cp.charsetForName(charsetName);
 412                             if (cs != null)
 413                                 return cs;
 414                         }
 415                         return null;
 416                     }
 417                 });
 418 
 419         } finally {
 420             gate.set(null);
 421         }
 422     }
 423 
 424     /* The extended set of charsets */
 425     private static class ExtendedProviderHolder {
 426         static final CharsetProvider[] extendedProviders = extendedProviders();
 427         // returns ExtendedProvider, if installed
 428         private static CharsetProvider[] extendedProviders() {
 429             return AccessController.doPrivileged(new PrivilegedAction<>() {
 430                     public CharsetProvider[] run() {
 431                         CharsetProvider[] cps = new CharsetProvider[1];
 432                         int n = 0;
 433                         ServiceLoader<CharsetProvider> sl =
 434                             ServiceLoader.loadInstalled(CharsetProvider.class);
 435                         for (CharsetProvider cp : sl) {
 436                             if (n + 1 > cps.length) {
 437                                 cps = Arrays.copyOf(cps, cps.length << 1);
 438                             }
 439                             cps[n++] = cp;
 440                         }
 441                         return n == cps.length ? cps : Arrays.copyOf(cps, n);
 442                     }});
 443         }
 444     }
 445 
 446     private static Charset lookupExtendedCharset(String charsetName) {
 447         if (!sun.misc.VM.isBooted())  // see lookupViaProviders()
 448             return null;
 449         CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders;
 450         for (CharsetProvider cp : ecps) {
 451             Charset cs = cp.charsetForName(charsetName);
 452             if (cs != null)
 453                 return cs;
 454         }
 455         return null;
 456     }
 457 
 458     private static Charset lookup(String charsetName) {
 459         if (charsetName == null)
 460             throw new IllegalArgumentException("Null charset name");
 461         Object[] a;
 462         if ((a = cache1) != null && charsetName.equals(a[0]))
 463             return (Charset)a[1];
 464         // We expect most programs to use one Charset repeatedly.
 465         // We convey a hint to this effect to the VM by putting the
 466         // level 1 cache miss code in a separate method.
 467         return lookup2(charsetName);
 468     }
 469 
 470     private static Charset lookup2(String charsetName) {
 471         Object[] a;
 472         if ((a = cache2) != null && charsetName.equals(a[0])) {
 473             cache2 = cache1;
 474             cache1 = a;
 475             return (Charset)a[1];
 476         }
 477         Charset cs;
 478         if ((cs = standardProvider.charsetForName(charsetName)) != null ||
 479             (cs = lookupExtendedCharset(charsetName))           != null ||
 480             (cs = lookupViaProviders(charsetName))              != null)
 481         {
 482             cache(charsetName, cs);
 483             return cs;
 484         }
 485 
 486         /* Only need to check the name if we didn't find a charset for it */
 487         checkName(charsetName);
 488         return null;
 489     }
 490 
 491     /**
 492      * Tells whether the named charset is supported.
 493      *
 494      * @param  charsetName
 495      *         The name of the requested charset; may be either
 496      *         a canonical name or an alias
 497      *
 498      * @return  <tt>true</tt> if, and only if, support for the named charset
 499      *          is available in the current Java virtual machine
 500      *
 501      * @throws IllegalCharsetNameException
 502      *         If the given charset name is illegal
 503      *
 504      * @throws  IllegalArgumentException
 505      *          If the given <tt>charsetName</tt> is null
 506      */
 507     public static boolean isSupported(String charsetName) {
 508         return (lookup(charsetName) != null);
 509     }
 510 
 511     /**
 512      * Returns a charset object for the named charset.
 513      *
 514      * @param  charsetName
 515      *         The name of the requested charset; may be either
 516      *         a canonical name or an alias
 517      *
 518      * @return  A charset object for the named charset
 519      *
 520      * @throws  IllegalCharsetNameException
 521      *          If the given charset name is illegal
 522      *
 523      * @throws  IllegalArgumentException
 524      *          If the given <tt>charsetName</tt> is null
 525      *
 526      * @throws  UnsupportedCharsetException
 527      *          If no support for the named charset is available
 528      *          in this instance of the Java virtual machine
 529      */
 530     public static Charset forName(String charsetName) {
 531         Charset cs = lookup(charsetName);
 532         if (cs != null)
 533             return cs;
 534         throw new UnsupportedCharsetException(charsetName);
 535     }
 536 
 537     // Fold charsets from the given iterator into the given map, ignoring
 538     // charsets whose names already have entries in the map.
 539     //
 540     private static void put(Iterator<Charset> i, Map<String,Charset> m) {
 541         while (i.hasNext()) {
 542             Charset cs = i.next();
 543             if (!m.containsKey(cs.name()))
 544                 m.put(cs.name(), cs);
 545         }
 546     }
 547 
 548     /**
 549      * Constructs a sorted map from canonical charset names to charset objects.
 550      *
 551      * <p> The map returned by this method will have one entry for each charset
 552      * for which support is available in the current Java virtual machine.  If
 553      * two or more supported charsets have the same canonical name then the
 554      * resulting map will contain just one of them; which one it will contain
 555      * is not specified. </p>
 556      *
 557      * <p> The invocation of this method, and the subsequent use of the
 558      * resulting map, may cause time-consuming disk or network I/O operations
 559      * to occur.  This method is provided for applications that need to
 560      * enumerate all of the available charsets, for example to allow user
 561      * charset selection.  This method is not used by the {@link #forName
 562      * forName} method, which instead employs an efficient incremental lookup
 563      * algorithm.
 564      *
 565      * <p> This method may return different results at different times if new
 566      * charset providers are dynamically made available to the current Java
 567      * virtual machine.  In the absence of such changes, the charsets returned
 568      * by this method are exactly those that can be retrieved via the {@link
 569      * #forName forName} method.  </p>
 570      *
 571      * @return An immutable, case-insensitive map from canonical charset names
 572      *         to charset objects
 573      */
 574     public static SortedMap<String,Charset> availableCharsets() {
 575         return AccessController.doPrivileged(
 576             new PrivilegedAction<>() {
 577                 public SortedMap<String,Charset> run() {
 578                     TreeMap<String,Charset> m =
 579                         new TreeMap<>(
 580                             ASCIICaseInsensitiveComparator.CASE_INSENSITIVE_ORDER);
 581                     put(standardProvider.charsets(), m);
 582                     CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders;
 583                     for (CharsetProvider ecp :ecps) {
 584                         put(ecp.charsets(), m);
 585                     }
 586                     for (Iterator<CharsetProvider> i = providers(); i.hasNext();) {
 587                         CharsetProvider cp = i.next();
 588                         put(cp.charsets(), m);
 589                     }
 590                     return Collections.unmodifiableSortedMap(m);
 591                 }
 592             });
 593     }
 594 
 595     private static volatile Charset defaultCharset;
 596 
 597     /**
 598      * Returns the default charset of this Java virtual machine.
 599      *
 600      * <p> The default charset is determined during virtual-machine startup and
 601      * typically depends upon the locale and charset of the underlying
 602      * operating system.
 603      *
 604      * @return  A charset object for the default charset
 605      *
 606      * @since 1.5
 607      */
 608     public static Charset defaultCharset() {
 609         if (defaultCharset == null) {
 610             synchronized (Charset.class) {
 611                 String csn = AccessController.doPrivileged(
 612                     new GetPropertyAction("file.encoding"));
 613                 Charset cs = lookup(csn);
 614                 if (cs != null)
 615                     defaultCharset = cs;
 616                 else
 617                     defaultCharset = forName("UTF-8");
 618             }
 619         }
 620         return defaultCharset;
 621     }
 622 
 623 
 624     /* -- Instance fields and methods -- */
 625 
 626     private final String name;          // tickles a bug in oldjavac
 627     private final String[] aliases;     // tickles a bug in oldjavac
 628     private Set<String> aliasSet = null;
 629 
 630     /**
 631      * Initializes a new charset with the given canonical name and alias
 632      * set.
 633      *
 634      * @param  canonicalName
 635      *         The canonical name of this charset
 636      *
 637      * @param  aliases
 638      *         An array of this charset's aliases, or null if it has no aliases
 639      *
 640      * @throws IllegalCharsetNameException
 641      *         If the canonical name or any of the aliases are illegal
 642      */
 643     protected Charset(String canonicalName, String[] aliases) {
 644         checkName(canonicalName);
 645         String[] as = (aliases == null) ? new String[0] : aliases;
 646         for (int i = 0; i < as.length; i++)
 647             checkName(as[i]);
 648         this.name = canonicalName;
 649         this.aliases = as;
 650     }
 651 
 652     /**
 653      * Returns this charset's canonical name.
 654      *
 655      * @return  The canonical name of this charset
 656      */
 657     public final String name() {
 658         return name;
 659     }
 660 
 661     /**
 662      * Returns a set containing this charset's aliases.
 663      *
 664      * @return  An immutable set of this charset's aliases
 665      */
 666     public final Set<String> aliases() {
 667         if (aliasSet != null)
 668             return aliasSet;
 669         int n = aliases.length;
 670         HashSet<String> hs = new HashSet<>(n);
 671         for (int i = 0; i < n; i++)
 672             hs.add(aliases[i]);
 673         aliasSet = Collections.unmodifiableSet(hs);
 674         return aliasSet;
 675     }
 676 
 677     /**
 678      * Returns this charset's human-readable name for the default locale.
 679      *
 680      * <p> The default implementation of this method simply returns this
 681      * charset's canonical name.  Concrete subclasses of this class may
 682      * override this method in order to provide a localized display name. </p>
 683      *
 684      * @return  The display name of this charset in the default locale
 685      */
 686     public String displayName() {
 687         return name;
 688     }
 689 
 690     /**
 691      * Tells whether or not this charset is registered in the <a
 692      * href="http://www.iana.org/assignments/character-sets">IANA Charset
 693      * Registry</a>.
 694      *
 695      * @return  <tt>true</tt> if, and only if, this charset is known by its
 696      *          implementor to be registered with the IANA
 697      */
 698     public final boolean isRegistered() {
 699         return !name.startsWith("X-") && !name.startsWith("x-");
 700     }
 701 
 702     /**
 703      * Returns this charset's human-readable name for the given locale.
 704      *
 705      * <p> The default implementation of this method simply returns this
 706      * charset's canonical name.  Concrete subclasses of this class may
 707      * override this method in order to provide a localized display name. </p>
 708      *
 709      * @param  locale
 710      *         The locale for which the display name is to be retrieved
 711      *
 712      * @return  The display name of this charset in the given locale
 713      */
 714     public String displayName(Locale locale) {
 715         return name;
 716     }
 717 
 718     /**
 719      * Tells whether or not this charset contains the given charset.
 720      *
 721      * <p> A charset <i>C</i> is said to <i>contain</i> a charset <i>D</i> if,
 722      * and only if, every character representable in <i>D</i> is also
 723      * representable in <i>C</i>.  If this relationship holds then it is
 724      * guaranteed that every string that can be encoded in <i>D</i> can also be
 725      * encoded in <i>C</i> without performing any replacements.
 726      *
 727      * <p> That <i>C</i> contains <i>D</i> does not imply that each character
 728      * representable in <i>C</i> by a particular byte sequence is represented
 729      * in <i>D</i> by the same byte sequence, although sometimes this is the
 730      * case.
 731      *
 732      * <p> Every charset contains itself.
 733      *
 734      * <p> This method computes an approximation of the containment relation:
 735      * If it returns <tt>true</tt> then the given charset is known to be
 736      * contained by this charset; if it returns <tt>false</tt>, however, then
 737      * it is not necessarily the case that the given charset is not contained
 738      * in this charset.
 739      *
 740      * @param   cs
 741      *          The given charset
 742      *
 743      * @return  <tt>true</tt> if the given charset is contained in this charset
 744      */
 745     public abstract boolean contains(Charset cs);
 746 
 747     /**
 748      * Constructs a new decoder for this charset.
 749      *
 750      * @return  A new decoder for this charset
 751      */
 752     public abstract CharsetDecoder newDecoder();
 753 
 754     /**
 755      * Constructs a new encoder for this charset.
 756      *
 757      * @return  A new encoder for this charset
 758      *
 759      * @throws  UnsupportedOperationException
 760      *          If this charset does not support encoding
 761      */
 762     public abstract CharsetEncoder newEncoder();
 763 
 764     /**
 765      * Tells whether or not this charset supports encoding.
 766      *
 767      * <p> Nearly all charsets support encoding.  The primary exceptions are
 768      * special-purpose <i>auto-detect</i> charsets whose decoders can determine
 769      * which of several possible encoding schemes is in use by examining the
 770      * input byte sequence.  Such charsets do not support encoding because
 771      * there is no way to determine which encoding should be used on output.
 772      * Implementations of such charsets should override this method to return
 773      * <tt>false</tt>. </p>
 774      *
 775      * @return  <tt>true</tt> if, and only if, this charset supports encoding
 776      */
 777     public boolean canEncode() {
 778         return true;
 779     }
 780 
 781     /**
 782      * Convenience method that decodes bytes in this charset into Unicode
 783      * characters.
 784      *
 785      * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
 786      * same result as the expression
 787      *
 788      * <pre>
 789      *     cs.newDecoder()
 790      *       .onMalformedInput(CodingErrorAction.REPLACE)
 791      *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
 792      *       .decode(bb); </pre>
 793      *
 794      * except that it is potentially more efficient because it can cache
 795      * decoders between successive invocations.
 796      *
 797      * <p> This method always replaces malformed-input and unmappable-character
 798      * sequences with this charset's default replacement byte array.  In order
 799      * to detect such sequences, use the {@link
 800      * CharsetDecoder#decode(java.nio.ByteBuffer)} method directly.  </p>
 801      *
 802      * @param  bb  The byte buffer to be decoded
 803      *
 804      * @return  A char buffer containing the decoded characters
 805      */
 806     public final CharBuffer decode(ByteBuffer bb) {
 807         try {
 808             return ThreadLocalCoders.decoderFor(this)
 809                 .onMalformedInput(CodingErrorAction.REPLACE)
 810                 .onUnmappableCharacter(CodingErrorAction.REPLACE)
 811                 .decode(bb);
 812         } catch (CharacterCodingException x) {
 813             throw new Error(x);         // Can't happen
 814         }
 815     }
 816 
 817     /**
 818      * Convenience method that encodes Unicode characters into bytes in this
 819      * charset.
 820      *
 821      * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
 822      * same result as the expression
 823      *
 824      * <pre>
 825      *     cs.newEncoder()
 826      *       .onMalformedInput(CodingErrorAction.REPLACE)
 827      *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
 828      *       .encode(bb); </pre>
 829      *
 830      * except that it is potentially more efficient because it can cache
 831      * encoders between successive invocations.
 832      *
 833      * <p> This method always replaces malformed-input and unmappable-character
 834      * sequences with this charset's default replacement string.  In order to
 835      * detect such sequences, use the {@link
 836      * CharsetEncoder#encode(java.nio.CharBuffer)} method directly.  </p>
 837      *
 838      * @param  cb  The char buffer to be encoded
 839      *
 840      * @return  A byte buffer containing the encoded characters
 841      */
 842     public final ByteBuffer encode(CharBuffer cb) {
 843         try {
 844             return ThreadLocalCoders.encoderFor(this)
 845                 .onMalformedInput(CodingErrorAction.REPLACE)
 846                 .onUnmappableCharacter(CodingErrorAction.REPLACE)
 847                 .encode(cb);
 848         } catch (CharacterCodingException x) {
 849             throw new Error(x);         // Can't happen
 850         }
 851     }
 852 
 853     /**
 854      * Convenience method that encodes a string into bytes in this charset.
 855      *
 856      * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
 857      * same result as the expression
 858      *
 859      * <pre>
 860      *     cs.encode(CharBuffer.wrap(s)); </pre>
 861      *
 862      * @param  str  The string to be encoded
 863      *
 864      * @return  A byte buffer containing the encoded characters
 865      */
 866     public final ByteBuffer encode(String str) {
 867         return encode(CharBuffer.wrap(str));
 868     }
 869 
 870     /**
 871      * Compares this charset to another.
 872      *
 873      * <p> Charsets are ordered by their canonical names, without regard to
 874      * case. </p>
 875      *
 876      * @param  that
 877      *         The charset to which this charset is to be compared
 878      *
 879      * @return A negative integer, zero, or a positive integer as this charset
 880      *         is less than, equal to, or greater than the specified charset
 881      */
 882     public final int compareTo(Charset that) {
 883         return (name().compareToIgnoreCase(that.name()));
 884     }
 885 
 886     /**
 887      * Computes a hashcode for this charset.
 888      *
 889      * @return  An integer hashcode
 890      */
 891     public final int hashCode() {
 892         return name().hashCode();
 893     }
 894 
 895     /**
 896      * Tells whether or not this object is equal to another.
 897      *
 898      * <p> Two charsets are equal if, and only if, they have the same canonical
 899      * names.  A charset is never equal to any other type of object.  </p>
 900      *
 901      * @return  <tt>true</tt> if, and only if, this charset is equal to the
 902      *          given object
 903      */
 904     public final boolean equals(Object ob) {
 905         if (!(ob instanceof Charset))
 906             return false;
 907         if (this == ob)
 908             return true;
 909         return name.equals(((Charset)ob).name());
 910     }
 911 
 912     /**
 913      * Returns a string describing this charset.
 914      *
 915      * @return  A string describing this charset
 916      */
 917     public final String toString() {
 918         return name();
 919     }
 920 
 921 }