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>'\u0041'</tt>&nbsp;through&nbsp;<tt>'\u005a'</tt>),
  78  *
  79  *   <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt>
  80  *        (<tt>'\u0061'</tt>&nbsp;through&nbsp;<tt>'\u007a'</tt>),
  81  *
  82  *   <li> The digits <tt>'0'</tt> through <tt>'9'</tt>
  83  *        (<tt>'\u0030'</tt>&nbsp;through&nbsp;<tt>'\u0039'</tt>),
  84  *
  85  *   <li> The dash character <tt>'-'</tt>
  86  *        (<tt>'\u002d'</tt>,&nbsp;<small>HYPHEN-MINUS</small>),
  87  *
  88  *   <li> The plus character <tt>'+'</tt>
  89  *        (<tt>'\u002b'</tt>,&nbsp;<small>PLUS SIGN</small>),
  90  *
  91  *   <li> The period character <tt>'.'</tt>
  92  *        (<tt>'\u002e'</tt>,&nbsp;<small>FULL STOP</small>),
  93  *
  94  *   <li> The colon character <tt>':'</tt>
  95  *        (<tt>'\u003a'</tt>,&nbsp;<small>COLON</small>), and
  96  *
  97  *   <li> The underscore character <tt>'_'</tt>
  98  *        (<tt>'\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>'\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     private static volatile Charset defaultUnicodeCharset;
 597 
 598     /**
 599      * Returns the default charset of this Java virtual machine.
 600      *
 601      * <p> The default charset is determined during virtual-machine startup and
 602      * typically depends upon the locale and charset of the underlying
 603      * operating system.
 604      *
 605      * @return  A charset object for the default charset
 606      *
 607      * @since 1.5
 608      */
 609     public static Charset defaultCharset() {
 610         if (defaultCharset == null) {
 611             synchronized (Charset.class) {
 612                 String csn = AccessController.doPrivileged(
 613                     new GetPropertyAction("file.encoding"));
 614                 Charset cs = lookup(csn);
 615                 if (cs != null)
 616                     defaultCharset = cs;
 617                 else
 618                     defaultCharset = forName("UTF-8");
 619             }
 620         }
 621         return defaultCharset;
 622     }
 623 
 624     /**
 625      * Returns the default unicode charset of this Java virtual machine.
 626      *
 627      * <p> The default unicode charset is determined during virtual-machine startup
 628      * and depends on command line option "file.encoding.unicode".
 629      * UTF8 is used by default.
 630      *
 631      * @return  A charset object for the default unicode charset
 632      *
 633      */
 634     public static Charset defaultUnicodeCharset() {
 635         if (defaultUnicodeCharset == null) {
 636             synchronized (Charset.class) {
 637                 defaultUnicodeCharset = forName("UTF-8");
 638 
 639                 String csn = AccessController.doPrivileged(
 640                     new GetPropertyAction("file.encoding.unicode"));
 641                 if (csn != null) {
 642                     Charset cs = lookup(csn);
 643                     if (cs != null) {
 644                         defaultUnicodeCharset = cs;
 645                     }
 646                 }
 647             }
 648         }
 649         return defaultUnicodeCharset;
 650     }
 651 
 652 
 653     /* -- Instance fields and methods -- */
 654 
 655     private final String name;          // tickles a bug in oldjavac
 656     private final String[] aliases;     // tickles a bug in oldjavac
 657     private Set<String> aliasSet = null;
 658 
 659     /**
 660      * Initializes a new charset with the given canonical name and alias
 661      * set.
 662      *
 663      * @param  canonicalName
 664      *         The canonical name of this charset
 665      *
 666      * @param  aliases
 667      *         An array of this charset's aliases, or null if it has no aliases
 668      *
 669      * @throws IllegalCharsetNameException
 670      *         If the canonical name or any of the aliases are illegal
 671      */
 672     protected Charset(String canonicalName, String[] aliases) {
 673         checkName(canonicalName);
 674         String[] as = (aliases == null) ? new String[0] : aliases;
 675         for (int i = 0; i < as.length; i++)
 676             checkName(as[i]);
 677         this.name = canonicalName;
 678         this.aliases = as;
 679     }
 680 
 681     /**
 682      * Returns this charset's canonical name.
 683      *
 684      * @return  The canonical name of this charset
 685      */
 686     public final String name() {
 687         return name;
 688     }
 689 
 690     /**
 691      * Returns a set containing this charset's aliases.
 692      *
 693      * @return  An immutable set of this charset's aliases
 694      */
 695     public final Set<String> aliases() {
 696         if (aliasSet != null)
 697             return aliasSet;
 698         int n = aliases.length;
 699         HashSet<String> hs = new HashSet<>(n);
 700         for (int i = 0; i < n; i++)
 701             hs.add(aliases[i]);
 702         aliasSet = Collections.unmodifiableSet(hs);
 703         return aliasSet;
 704     }
 705 
 706     /**
 707      * Returns this charset's human-readable name for the default locale.
 708      *
 709      * <p> The default implementation of this method simply returns this
 710      * charset's canonical name.  Concrete subclasses of this class may
 711      * override this method in order to provide a localized display name. </p>
 712      *
 713      * @return  The display name of this charset in the default locale
 714      */
 715     public String displayName() {
 716         return name;
 717     }
 718 
 719     /**
 720      * Tells whether or not this charset is registered in the <a
 721      * href="http://www.iana.org/assignments/character-sets">IANA Charset
 722      * Registry</a>.
 723      *
 724      * @return  <tt>true</tt> if, and only if, this charset is known by its
 725      *          implementor to be registered with the IANA
 726      */
 727     public final boolean isRegistered() {
 728         return !name.startsWith("X-") && !name.startsWith("x-");
 729     }
 730 
 731     /**
 732      * Returns this charset's human-readable name for the given locale.
 733      *
 734      * <p> The default implementation of this method simply returns this
 735      * charset's canonical name.  Concrete subclasses of this class may
 736      * override this method in order to provide a localized display name. </p>
 737      *
 738      * @param  locale
 739      *         The locale for which the display name is to be retrieved
 740      *
 741      * @return  The display name of this charset in the given locale
 742      */
 743     public String displayName(Locale locale) {
 744         return name;
 745     }
 746 
 747     /**
 748      * Tells whether or not this charset contains the given charset.
 749      *
 750      * <p> A charset <i>C</i> is said to <i>contain</i> a charset <i>D</i> if,
 751      * and only if, every character representable in <i>D</i> is also
 752      * representable in <i>C</i>.  If this relationship holds then it is
 753      * guaranteed that every string that can be encoded in <i>D</i> can also be
 754      * encoded in <i>C</i> without performing any replacements.
 755      *
 756      * <p> That <i>C</i> contains <i>D</i> does not imply that each character
 757      * representable in <i>C</i> by a particular byte sequence is represented
 758      * in <i>D</i> by the same byte sequence, although sometimes this is the
 759      * case.
 760      *
 761      * <p> Every charset contains itself.
 762      *
 763      * <p> This method computes an approximation of the containment relation:
 764      * If it returns <tt>true</tt> then the given charset is known to be
 765      * contained by this charset; if it returns <tt>false</tt>, however, then
 766      * it is not necessarily the case that the given charset is not contained
 767      * in this charset.
 768      *
 769      * @param   cs
 770      *          The given charset
 771      *
 772      * @return  <tt>true</tt> if the given charset is contained in this charset
 773      */
 774     public abstract boolean contains(Charset cs);
 775 
 776     /**
 777      * Constructs a new decoder for this charset.
 778      *
 779      * @return  A new decoder for this charset
 780      */
 781     public abstract CharsetDecoder newDecoder();
 782 
 783     /**
 784      * Constructs a new encoder for this charset.
 785      *
 786      * @return  A new encoder for this charset
 787      *
 788      * @throws  UnsupportedOperationException
 789      *          If this charset does not support encoding
 790      */
 791     public abstract CharsetEncoder newEncoder();
 792 
 793     /**
 794      * Tells whether or not this charset supports encoding.
 795      *
 796      * <p> Nearly all charsets support encoding.  The primary exceptions are
 797      * special-purpose <i>auto-detect</i> charsets whose decoders can determine
 798      * which of several possible encoding schemes is in use by examining the
 799      * input byte sequence.  Such charsets do not support encoding because
 800      * there is no way to determine which encoding should be used on output.
 801      * Implementations of such charsets should override this method to return
 802      * <tt>false</tt>. </p>
 803      *
 804      * @return  <tt>true</tt> if, and only if, this charset supports encoding
 805      */
 806     public boolean canEncode() {
 807         return true;
 808     }
 809 
 810     /**
 811      * Convenience method that decodes bytes in this charset into Unicode
 812      * characters.
 813      *
 814      * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
 815      * same result as the expression
 816      *
 817      * <pre>
 818      *     cs.newDecoder()
 819      *       .onMalformedInput(CodingErrorAction.REPLACE)
 820      *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
 821      *       .decode(bb); </pre>
 822      *
 823      * except that it is potentially more efficient because it can cache
 824      * decoders between successive invocations.
 825      *
 826      * <p> This method always replaces malformed-input and unmappable-character
 827      * sequences with this charset's default replacement byte array.  In order
 828      * to detect such sequences, use the {@link
 829      * CharsetDecoder#decode(java.nio.ByteBuffer)} method directly.  </p>
 830      *
 831      * @param  bb  The byte buffer to be decoded
 832      *
 833      * @return  A char buffer containing the decoded characters
 834      */
 835     public final CharBuffer decode(ByteBuffer bb) {
 836         try {
 837             return ThreadLocalCoders.decoderFor(this)
 838                 .onMalformedInput(CodingErrorAction.REPLACE)
 839                 .onUnmappableCharacter(CodingErrorAction.REPLACE)
 840                 .decode(bb);
 841         } catch (CharacterCodingException x) {
 842             throw new Error(x);         // Can't happen
 843         }
 844     }
 845 
 846     /**
 847      * Convenience method that encodes Unicode characters into bytes in this
 848      * charset.
 849      *
 850      * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
 851      * same result as the expression
 852      *
 853      * <pre>
 854      *     cs.newEncoder()
 855      *       .onMalformedInput(CodingErrorAction.REPLACE)
 856      *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
 857      *       .encode(bb); </pre>
 858      *
 859      * except that it is potentially more efficient because it can cache
 860      * encoders between successive invocations.
 861      *
 862      * <p> This method always replaces malformed-input and unmappable-character
 863      * sequences with this charset's default replacement string.  In order to
 864      * detect such sequences, use the {@link
 865      * CharsetEncoder#encode(java.nio.CharBuffer)} method directly.  </p>
 866      *
 867      * @param  cb  The char buffer to be encoded
 868      *
 869      * @return  A byte buffer containing the encoded characters
 870      */
 871     public final ByteBuffer encode(CharBuffer cb) {
 872         try {
 873             return ThreadLocalCoders.encoderFor(this)
 874                 .onMalformedInput(CodingErrorAction.REPLACE)
 875                 .onUnmappableCharacter(CodingErrorAction.REPLACE)
 876                 .encode(cb);
 877         } catch (CharacterCodingException x) {
 878             throw new Error(x);         // Can't happen
 879         }
 880     }
 881 
 882     /**
 883      * Convenience method that encodes a string into bytes in this charset.
 884      *
 885      * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
 886      * same result as the expression
 887      *
 888      * <pre>
 889      *     cs.encode(CharBuffer.wrap(s)); </pre>
 890      *
 891      * @param  str  The string to be encoded
 892      *
 893      * @return  A byte buffer containing the encoded characters
 894      */
 895     public final ByteBuffer encode(String str) {
 896         return encode(CharBuffer.wrap(str));
 897     }
 898 
 899     /**
 900      * Compares this charset to another.
 901      *
 902      * <p> Charsets are ordered by their canonical names, without regard to
 903      * case. </p>
 904      *
 905      * @param  that
 906      *         The charset to which this charset is to be compared
 907      *
 908      * @return A negative integer, zero, or a positive integer as this charset
 909      *         is less than, equal to, or greater than the specified charset
 910      */
 911     public final int compareTo(Charset that) {
 912         return (name().compareToIgnoreCase(that.name()));
 913     }
 914 
 915     /**
 916      * Computes a hashcode for this charset.
 917      *
 918      * @return  An integer hashcode
 919      */
 920     public final int hashCode() {
 921         return name().hashCode();
 922     }
 923 
 924     /**
 925      * Tells whether or not this object is equal to another.
 926      *
 927      * <p> Two charsets are equal if, and only if, they have the same canonical
 928      * names.  A charset is never equal to any other type of object.  </p>
 929      *
 930      * @return  <tt>true</tt> if, and only if, this charset is equal to the
 931      *          given object
 932      */
 933     public final boolean equals(Object ob) {
 934         if (!(ob instanceof Charset))
 935             return false;
 936         if (this == ob)
 937             return true;
 938         return name.equals(((Charset)ob).name());
 939     }
 940 
 941     /**
 942      * Returns a string describing this charset.
 943      *
 944      * @return  A string describing this charset
 945      */
 946     public final String toString() {
 947         return name();
 948     }
 949 
 950 }