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