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