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>'\u0041'</tt> through <tt>'\u005a'</tt>), 78 * 79 * <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt> 80 * (<tt>'\u0061'</tt> through <tt>'\u007a'</tt>), 81 * 82 * <li> The digits <tt>'0'</tt> through <tt>'9'</tt> 83 * (<tt>'\u0030'</tt> through <tt>'\u0039'</tt>), 84 * 85 * <li> The dash character <tt>'-'</tt> 86 * (<tt>'\u002d'</tt>, <small>HYPHEN-MINUS</small>), 87 * 88 * <li> The plus character <tt>'+'</tt> 89 * (<tt>'\u002b'</tt>, <small>PLUS SIGN</small>), 90 * 91 * <li> The period character <tt>'.'</tt> 92 * (<tt>'\u002e'</tt>, <small>FULL STOP</small>), 93 * 94 * <li> The colon character <tt>':'</tt> 95 * (<tt>'\u003a'</tt>, <small>COLON</small>), and 96 * 97 * <li> The underscore character <tt>'_'</tt> 98 * (<tt>'\u005f'</tt>, <small>LOW 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 2278: 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 * <p> Every implementation of the Java platform is required to support the 147 * following standard charsets. Consult the release documentation for your 148 * implementation to see if any other charsets are supported. The behavior 149 * of such optional charsets may differ between implementations. 150 * 151 * <blockquote><table width="80%" summary="Description of standard charsets"> 152 * <tr><th><p align="left">Charset</p></th><th><p align="left">Description</p></th></tr> 153 * <tr><td valign=top><tt>US-ASCII</tt></td> 154 * <td>Seven-bit ASCII, a.k.a. <tt>ISO646-US</tt>, 155 * a.k.a. the Basic Latin block of the Unicode character set</td></tr> 156 * <tr><td valign=top><tt>ISO-8859-1 </tt></td> 157 * <td>ISO Latin Alphabet No. 1, a.k.a. <tt>ISO-LATIN-1</tt></td></tr> 158 * <tr><td valign=top><tt>UTF-8</tt></td> 159 * <td>Eight-bit UCS Transformation Format</td></tr> 160 * <tr><td valign=top><tt>UTF-16BE</tt></td> 161 * <td>Sixteen-bit UCS Transformation Format, 162 * big-endian byte order</td></tr> 163 * <tr><td valign=top><tt>UTF-16LE</tt></td> 164 * <td>Sixteen-bit UCS Transformation Format, 165 * little-endian byte order</td></tr> 166 * <tr><td valign=top><tt>UTF-16</tt></td> 167 * <td>Sixteen-bit UCS Transformation Format, 168 * byte order identified by an optional byte-order mark</td></tr> 169 * </table></blockquote> 170 * 171 * <p> The <tt>UTF-8</tt> charset is specified by <a 172 * href="http://www.ietf.org/rfc/rfc2279.txt"><i>RFC 2279</i></a>; the 173 * transformation format upon which it is based is specified in 174 * Amendment 2 of ISO 10646-1 and is also described in the <a 175 * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode 176 * Standard</i></a>. 177 * 178 * <p> The <tt>UTF-16</tt> charsets are specified by <a 179 * href="http://www.ietf.org/rfc/rfc2781.txt"><i>RFC 2781</i></a>; the 180 * transformation formats upon which they are based are specified in 181 * Amendment 1 of ISO 10646-1 and are also described in the <a 182 * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode 183 * Standard</i></a>. 184 * 185 * <p> The <tt>UTF-16</tt> charsets use sixteen-bit quantities and are 186 * therefore sensitive to byte order. In these encodings the byte order of a 187 * stream may be indicated by an initial <i>byte-order mark</i> represented by 188 * the Unicode character <tt>'\uFEFF'</tt>. Byte-order marks are handled 189 * as follows: 190 * 191 * <ul> 192 * 193 * <li><p> When decoding, the <tt>UTF-16BE</tt> and <tt>UTF-16LE</tt> 194 * charsets interpret the initial byte-order marks as a <small>ZERO-WIDTH 195 * NON-BREAKING SPACE</small>; when encoding, they do not write 196 * byte-order marks. </p></li> 197 198 * 199 * <li><p> When decoding, the <tt>UTF-16</tt> charset interprets the 200 * byte-order mark at the beginning of the input stream to indicate the 201 * byte-order of the stream but defaults to big-endian if there is no 202 * byte-order mark; when encoding, it uses big-endian byte order and writes 203 * a big-endian byte-order mark. </p></li> 204 * 205 * </ul> 206 * 207 * In any case, byte order marks occuring after the first element of an 208 * input sequence are not omitted since the same code is used to represent 209 * <small>ZERO-WIDTH NON-BREAKING SPACE</small>. 210 * 211 * <p> Every instance of the Java virtual machine has a default charset, which 212 * may or may not be one of the standard charsets. The default charset is 213 * determined during virtual-machine startup and typically depends upon the 214 * locale and charset being used by the underlying operating system. </p> 215 * 216 * 217 * <h4>Terminology</h4> 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 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 8859-1, 228 * JIS X 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 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 X 0201, JIS X 0208, and JIS X 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 providers() { 339 return new Iterator() { 340 341 ClassLoader cl = ClassLoader.getSystemClassLoader(); 342 ServiceLoader<CharsetProvider> sl = 343 ServiceLoader.load(CharsetProvider.class, cl); 344 Iterator<CharsetProvider> i = sl.iterator(); 345 346 Object next = null; 347 348 private boolean getNext() { 349 while (next == null) { 350 try { 351 if (!i.hasNext()) 352 return false; 353 next = i.next(); 354 } catch (ServiceConfigurationError sce) { 355 if (sce.getCause() instanceof SecurityException) { 356 // Ignore security exceptions 357 continue; 358 } 359 throw sce; 360 } 361 } 362 return true; 363 } 364 365 public boolean hasNext() { 366 return getNext(); 367 } 368 369 public Object next() { 370 if (!getNext()) 371 throw new NoSuchElementException(); 372 Object n = next; 373 next = null; 374 return n; 375 } 376 377 public void remove() { 378 throw new UnsupportedOperationException(); 379 } 380 381 }; 382 } 383 384 // Thread-local gate to prevent recursive provider lookups 385 private static ThreadLocal<ThreadLocal> gate = new ThreadLocal<ThreadLocal>(); 386 387 private static Charset lookupViaProviders(final String charsetName) { 388 389 // The runtime startup sequence looks up standard charsets as a 390 // consequence of the VM's invocation of System.initializeSystemClass 391 // in order to, e.g., set system properties and encode filenames. At 392 // that point the application class loader has not been initialized, 393 // however, so we can't look for providers because doing so will cause 394 // that loader to be prematurely initialized with incomplete 395 // information. 396 // 397 if (!sun.misc.VM.isBooted()) 398 return null; 399 400 if (gate.get() != null) 401 // Avoid recursive provider lookups 402 return null; 403 try { 404 gate.set(gate); 405 406 return AccessController.doPrivileged( 407 new PrivilegedAction<Charset>() { 408 public Charset run() { 409 for (Iterator i = providers(); i.hasNext();) { 410 CharsetProvider cp = (CharsetProvider)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 Object extendedProviderLock = new Object(); 426 private static boolean extendedProviderProbed = false; 427 private static CharsetProvider extendedProvider = null; 428 429 private static void probeExtendedProvider() { 430 AccessController.doPrivileged(new PrivilegedAction<Object>() { 431 public Object run() { 432 try { 433 Class epc 434 = Class.forName("sun.nio.cs.ext.ExtendedCharsets"); 435 extendedProvider = (CharsetProvider)epc.newInstance(); 436 } catch (ClassNotFoundException x) { 437 // Extended charsets not available 438 // (charsets.jar not present) 439 } catch (InstantiationException x) { 440 throw new Error(x); 441 } catch (IllegalAccessException x) { 442 throw new Error(x); 443 } 444 return null; 445 } 446 }); 447 } 448 449 private static Charset lookupExtendedCharset(String charsetName) { 450 CharsetProvider ecp = null; 451 synchronized (extendedProviderLock) { 452 if (!extendedProviderProbed) { 453 probeExtendedProvider(); 454 extendedProviderProbed = true; 455 } 456 ecp = extendedProvider; 457 } 458 return (ecp != null) ? ecp.charsetForName(charsetName) : null; 459 } 460 461 private static Charset lookup(String charsetName) { 462 if (charsetName == null) 463 throw new IllegalArgumentException("Null charset name"); 464 465 Object[] a; 466 if ((a = cache1) != null && charsetName.equals(a[0])) 467 return (Charset)a[1]; 468 // We expect most programs to use one Charset repeatedly. 469 // We convey a hint to this effect to the VM by putting the 470 // level 1 cache miss code in a separate method. 471 return lookup2(charsetName); 472 } 473 474 private static Charset lookup2(String charsetName) { 475 Object[] a; 476 if ((a = cache2) != null && charsetName.equals(a[0])) { 477 cache2 = cache1; 478 cache1 = a; 479 return (Charset)a[1]; 480 } 481 482 Charset cs; 483 if ((cs = standardProvider.charsetForName(charsetName)) != null || 484 (cs = lookupExtendedCharset(charsetName)) != null || 485 (cs = lookupViaProviders(charsetName)) != null) 486 { 487 cache(charsetName, cs); 488 return cs; 489 } 490 491 /* Only need to check the name if we didn't find a charset for it */ 492 checkName(charsetName); 493 return null; 494 } 495 496 /** 497 * Tells whether the named charset is supported. </p> 498 * 499 * @param charsetName 500 * The name of the requested charset; may be either 501 * a canonical name or an alias 502 * 503 * @return <tt>true</tt> if, and only if, support for the named charset 504 * is available in the current Java virtual machine 505 * 506 * @throws IllegalCharsetNameException 507 * If the given charset name is illegal 508 * 509 * @throws IllegalArgumentException 510 * If the given <tt>charsetName</tt> is null 511 */ 512 public static boolean isSupported(String charsetName) { 513 return (lookup(charsetName) != null); 514 } 515 516 /** 517 * Returns a charset object for the named charset. </p> 518 * 519 * @param charsetName 520 * The name of the requested charset; may be either 521 * a canonical name or an alias 522 * 523 * @return A charset object for the named charset 524 * 525 * @throws IllegalCharsetNameException 526 * If the given charset name is illegal 527 * 528 * @throws IllegalArgumentException 529 * If the given <tt>charsetName</tt> is null 530 * 531 * @throws UnsupportedCharsetException 532 * If no support for the named charset is available 533 * in this instance of the Java virtual machine 534 */ 535 public static Charset forName(String charsetName) { 536 Charset cs = lookup(charsetName); 537 if (cs != null) 538 return cs; 539 throw new UnsupportedCharsetException(charsetName); 540 } 541 542 // Fold charsets from the given iterator into the given map, ignoring 543 // charsets whose names already have entries in the map. 544 // 545 private static void put(Iterator<Charset> i, Map<String,Charset> m) { 546 while (i.hasNext()) { 547 Charset cs = i.next(); 548 if (!m.containsKey(cs.name())) 549 m.put(cs.name(), cs); 550 } 551 } 552 553 /** 554 * Constructs a sorted map from canonical charset names to charset objects. 555 * 556 * <p> The map returned by this method will have one entry for each charset 557 * for which support is available in the current Java virtual machine. If 558 * two or more supported charsets have the same canonical name then the 559 * resulting map will contain just one of them; which one it will contain 560 * is not specified. </p> 561 * 562 * <p> The invocation of this method, and the subsequent use of the 563 * resulting map, may cause time-consuming disk or network I/O operations 564 * to occur. This method is provided for applications that need to 565 * enumerate all of the available charsets, for example to allow user 566 * charset selection. This method is not used by the {@link #forName 567 * forName} method, which instead employs an efficient incremental lookup 568 * algorithm. 569 * 570 * <p> This method may return different results at different times if new 571 * charset providers are dynamically made available to the current Java 572 * virtual machine. In the absence of such changes, the charsets returned 573 * by this method are exactly those that can be retrieved via the {@link 574 * #forName forName} method. </p> 575 * 576 * @return An immutable, case-insensitive map from canonical charset names 577 * to charset objects 578 */ 579 public static SortedMap<String,Charset> availableCharsets() { 580 return AccessController.doPrivileged( 581 new PrivilegedAction<SortedMap<String,Charset>>() { 582 public SortedMap<String,Charset> run() { 583 TreeMap<String,Charset> m = 584 new TreeMap<String,Charset>( 585 ASCIICaseInsensitiveComparator.CASE_INSENSITIVE_ORDER); 586 put(standardProvider.charsets(), m); 587 for (Iterator i = providers(); i.hasNext();) { 588 CharsetProvider cp = (CharsetProvider)i.next(); 589 put(cp.charsets(), m); 590 } 591 return Collections.unmodifiableSortedMap(m); 592 } 593 }); 594 } 595 596 private static volatile Charset defaultCharset; 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 /* -- Instance fields and methods -- */ 626 627 private final String name; // tickles a bug in oldjavac 628 private final String[] aliases; // tickles a bug in oldjavac 629 private Set<String> aliasSet = null; 630 631 /** 632 * Initializes a new charset with the given canonical name and alias 633 * set. </p> 634 * 635 * @param canonicalName 636 * The canonical name of this charset 637 * 638 * @param aliases 639 * An array of this charset's aliases, or null if it has no aliases 640 * 641 * @throws IllegalCharsetNameException 642 * If the canonical name or any of the aliases are illegal 643 */ 644 protected Charset(String canonicalName, String[] aliases) { 645 checkName(canonicalName); 646 String[] as = (aliases == null) ? new String[0] : aliases; 647 for (int i = 0; i < as.length; i++) 648 checkName(as[i]); 649 this.name = canonicalName; 650 this.aliases = as; 651 } 652 653 /** 654 * Returns this charset's canonical name. </p> 655 * 656 * @return The canonical name of this charset 657 */ 658 public final String name() { 659 return name; 660 } 661 662 /** 663 * Returns a set containing this charset's aliases. </p> 664 * 665 * @return An immutable set of this charset's aliases 666 */ 667 public final Set<String> aliases() { 668 if (aliasSet != null) 669 return aliasSet; 670 int n = aliases.length; 671 HashSet<String> hs = new HashSet<String>(n); 672 for (int i = 0; i < n; i++) 673 hs.add(aliases[i]); 674 aliasSet = Collections.unmodifiableSet(hs); 675 return aliasSet; 676 } 677 678 /** 679 * Returns this charset's human-readable name for the default locale. 680 * 681 * <p> The default implementation of this method simply returns this 682 * charset's canonical name. Concrete subclasses of this class may 683 * override this method in order to provide a localized display name. </p> 684 * 685 * @return The display name of this charset in the default locale 686 */ 687 public String displayName() { 688 return name; 689 } 690 691 /** 692 * Tells whether or not this charset is registered in the <a 693 * href="http://www.iana.org/assignments/character-sets">IANA Charset 694 * Registry</a>. </p> 695 * 696 * @return <tt>true</tt> if, and only if, this charset is known by its 697 * implementor to be registered with the IANA 698 */ 699 public final boolean isRegistered() { 700 return !name.startsWith("X-") && !name.startsWith("x-"); 701 } 702 703 /** 704 * Returns this charset's human-readable name for the given locale. 705 * 706 * <p> The default implementation of this method simply returns this 707 * charset's canonical name. Concrete subclasses of this class may 708 * override this method in order to provide a localized display name. </p> 709 * 710 * @param locale 711 * The locale for which the display name is to be retrieved 712 * 713 * @return The display name of this charset in the given locale 714 */ 715 public String displayName(Locale locale) { 716 return name; 717 } 718 719 /** 720 * Tells whether or not this charset contains the given charset. 721 * 722 * <p> A charset <i>C</i> is said to <i>contain</i> a charset <i>D</i> if, 723 * and only if, every character representable in <i>D</i> is also 724 * representable in <i>C</i>. If this relationship holds then it is 725 * guaranteed that every string that can be encoded in <i>D</i> can also be 726 * encoded in <i>C</i> without performing any replacements. 727 * 728 * <p> That <i>C</i> contains <i>D</i> does not imply that each character 729 * representable in <i>C</i> by a particular byte sequence is represented 730 * in <i>D</i> by the same byte sequence, although sometimes this is the 731 * case. 732 * 733 * <p> Every charset contains itself. 734 * 735 * <p> This method computes an approximation of the containment relation: 736 * If it returns <tt>true</tt> then the given charset is known to be 737 * contained by this charset; if it returns <tt>false</tt>, however, then 738 * it is not necessarily the case that the given charset is not contained 739 * in this charset. 740 * 741 * @return <tt>true</tt> if the given charset is contained in this charset 742 */ 743 public abstract boolean contains(Charset cs); 744 745 /** 746 * Constructs a new decoder for this charset. </p> 747 * 748 * @return A new decoder for this charset 749 */ 750 public abstract CharsetDecoder newDecoder(); 751 752 /** 753 * Constructs a new encoder for this charset. </p> 754 * 755 * @return A new encoder for this charset 756 * 757 * @throws UnsupportedOperationException 758 * If this charset does not support encoding 759 */ 760 public abstract CharsetEncoder newEncoder(); 761 762 /** 763 * Tells whether or not this charset supports encoding. 764 * 765 * <p> Nearly all charsets support encoding. The primary exceptions are 766 * special-purpose <i>auto-detect</i> charsets whose decoders can determine 767 * which of several possible encoding schemes is in use by examining the 768 * input byte sequence. Such charsets do not support encoding because 769 * there is no way to determine which encoding should be used on output. 770 * Implementations of such charsets should override this method to return 771 * <tt>false</tt>. </p> 772 * 773 * @return <tt>true</tt> if, and only if, this charset supports encoding 774 */ 775 public boolean canEncode() { 776 return true; 777 } 778 779 /** 780 * Convenience method that decodes bytes in this charset into Unicode 781 * characters. 782 * 783 * <p> An invocation of this method upon a charset <tt>cs</tt> returns the 784 * same result as the expression 785 * 786 * <pre> 787 * cs.newDecoder() 788 * .onMalformedInput(CodingErrorAction.REPLACE) 789 * .onUnmappableCharacter(CodingErrorAction.REPLACE) 790 * .decode(bb); </pre> 791 * 792 * except that it is potentially more efficient because it can cache 793 * decoders between successive invocations. 794 * 795 * <p> This method always replaces malformed-input and unmappable-character 796 * sequences with this charset's default replacement byte array. In order 797 * to detect such sequences, use the {@link 798 * CharsetDecoder#decode(java.nio.ByteBuffer)} method directly. </p> 799 * 800 * @param bb The byte buffer to be decoded 801 * 802 * @return A char buffer containing the decoded characters 803 */ 804 public final CharBuffer decode(ByteBuffer bb) { 805 try { 806 return ThreadLocalCoders.decoderFor(this) 807 .onMalformedInput(CodingErrorAction.REPLACE) 808 .onUnmappableCharacter(CodingErrorAction.REPLACE) 809 .decode(bb); 810 } catch (CharacterCodingException x) { 811 throw new Error(x); // Can't happen 812 } 813 } 814 815 /** 816 * Convenience method that encodes Unicode characters into bytes in this 817 * charset. 818 * 819 * <p> An invocation of this method upon a charset <tt>cs</tt> returns the 820 * same result as the expression 821 * 822 * <pre> 823 * cs.newEncoder() 824 * .onMalformedInput(CodingErrorAction.REPLACE) 825 * .onUnmappableCharacter(CodingErrorAction.REPLACE) 826 * .encode(bb); </pre> 827 * 828 * except that it is potentially more efficient because it can cache 829 * encoders between successive invocations. 830 * 831 * <p> This method always replaces malformed-input and unmappable-character 832 * sequences with this charset's default replacement string. In order to 833 * detect such sequences, use the {@link 834 * CharsetEncoder#encode(java.nio.CharBuffer)} method directly. </p> 835 * 836 * @param cb The char buffer to be encoded 837 * 838 * @return A byte buffer containing the encoded characters 839 */ 840 public final ByteBuffer encode(CharBuffer cb) { 841 try { 842 return ThreadLocalCoders.encoderFor(this) 843 .onMalformedInput(CodingErrorAction.REPLACE) 844 .onUnmappableCharacter(CodingErrorAction.REPLACE) 845 .encode(cb); 846 } catch (CharacterCodingException x) { 847 throw new Error(x); // Can't happen 848 } 849 } 850 851 /** 852 * Convenience method that encodes a string into bytes in this charset. 853 * 854 * <p> An invocation of this method upon a charset <tt>cs</tt> returns the 855 * same result as the expression 856 * 857 * <pre> 858 * cs.encode(CharBuffer.wrap(s)); </pre> 859 * 860 * @param str The string to be encoded 861 * 862 * @return A byte buffer containing the encoded characters 863 */ 864 public final ByteBuffer encode(String str) { 865 return encode(CharBuffer.wrap(str)); 866 } 867 868 /** 869 * Compares this charset to another. 870 * 871 * <p> Charsets are ordered by their canonical names, without regard to 872 * case. </p> 873 * 874 * @param that 875 * The charset to which this charset is to be compared 876 * 877 * @return A negative integer, zero, or a positive integer as this charset 878 * is less than, equal to, or greater than the specified charset 879 */ 880 public final int compareTo(Charset that) { 881 return (name().compareToIgnoreCase(that.name())); 882 } 883 884 /** 885 * Computes a hashcode for this charset. </p> 886 * 887 * @return An integer hashcode 888 */ 889 public final int hashCode() { 890 return name().hashCode(); 891 } 892 893 /** 894 * Tells whether or not this object is equal to another. 895 * 896 * <p> Two charsets are equal if, and only if, they have the same canonical 897 * names. A charset is never equal to any other type of object. </p> 898 * 899 * @return <tt>true</tt> if, and only if, this charset is equal to the 900 * given object 901 */ 902 public final boolean equals(Object ob) { 903 if (!(ob instanceof Charset)) 904 return false; 905 if (this == ob) 906 return true; 907 return name.equals(((Charset)ob).name()); 908 } 909 910 /** 911 * Returns a string describing this charset. </p> 912 * 913 * @return A string describing this charset 914 */ 915 public final String toString() { 916 return name(); 917 } 918 919 }