8187443: Forest Consolidation: Move files to unified layout

Reviewed-by: darcy, ihse
This commit is contained in:
Erik Joelsson 2017-09-12 19:03:39 +02:00
parent 270fe13182
commit 3789983e89
56923 changed files with 3 additions and 15727 deletions

View file

@ -0,0 +1,993 @@
/*
* Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#warn This file is preprocessed before being compiled
package java.nio.charset;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.lang.ref.WeakReference;
import java.nio.charset.CoderMalfunctionError; // javadoc
import java.util.Arrays;
/**
* An engine that can transform a sequence of $itypesPhrase$ into a sequence of
* $otypesPhrase$.
*
* <a id="steps"></a>
*
* <p> The input $itype$ sequence is provided in a $itype$ buffer or a series
* of such buffers. The output $otype$ sequence is written to a $otype$ buffer
* or a series of such buffers. $A$ $coder$ should always be used by making
* the following sequence of method invocations, hereinafter referred to as $a$
* <i>$coding$ operation</i>:
*
* <ol>
*
* <li><p> Reset the $coder$ via the {@link #reset reset} method, unless it
* has not been used before; </p></li>
*
* <li><p> Invoke the {@link #$code$ $code$} method zero or more times, as
* long as additional input may be available, passing {@code false} for the
* {@code endOfInput} argument and filling the input buffer and flushing the
* output buffer between invocations; </p></li>
*
* <li><p> Invoke the {@link #$code$ $code$} method one final time, passing
* {@code true} for the {@code endOfInput} argument; and then </p></li>
*
* <li><p> Invoke the {@link #flush flush} method so that the $coder$ can
* flush any internal state to the output buffer. </p></li>
*
* </ol>
*
* Each invocation of the {@link #$code$ $code$} method will $code$ as many
* $itype$s as possible from the input buffer, writing the resulting $otype$s
* to the output buffer. The {@link #$code$ $code$} method returns when more
* input is required, when there is not enough room in the output buffer, or
* when $a$ $coding$ error has occurred. In each case a {@link CoderResult}
* object is returned to describe the reason for termination. An invoker can
* examine this object and fill the input buffer, flush the output buffer, or
* attempt to recover from $a$ $coding$ error, as appropriate, and try again.
*
* <a id="ce"></a>
*
* <p> There are two general types of $coding$ errors. If the input $itype$
* sequence is $notLegal$ then the input is considered <i>malformed</i>. If
* the input $itype$ sequence is legal but cannot be mapped to a valid
* $outSequence$ then an <i>unmappable character</i> has been encountered.
*
* <a id="cae"></a>
*
* <p> How $a$ $coding$ error is handled depends upon the action requested for
* that type of error, which is described by an instance of the {@link
* CodingErrorAction} class. The possible error actions are to {@linkplain
* CodingErrorAction#IGNORE ignore} the erroneous input, {@linkplain
* CodingErrorAction#REPORT report} the error to the invoker via
* the returned {@link CoderResult} object, or {@linkplain CodingErrorAction#REPLACE
* replace} the erroneous input with the current value of the
* replacement $replTypeName$. The replacement
*
#if[encoder]
* is initially set to the $coder$'s default replacement, which often
* (but not always) has the initial value&nbsp;$defaultReplName$;
#end[encoder]
#if[decoder]
* has the initial value $defaultReplName$;
#end[decoder]
*
* its value may be changed via the {@link #replaceWith($replFQType$)
* replaceWith} method.
*
* <p> The default action for malformed-input and unmappable-character errors
* is to {@linkplain CodingErrorAction#REPORT report} them. The
* malformed-input error action may be changed via the {@link
* #onMalformedInput(CodingErrorAction) onMalformedInput} method; the
* unmappable-character action may be changed via the {@link
* #onUnmappableCharacter(CodingErrorAction) onUnmappableCharacter} method.
*
* <p> This class is designed to handle many of the details of the $coding$
* process, including the implementation of error actions. $A$ $coder$ for a
* specific charset, which is a concrete subclass of this class, need only
* implement the abstract {@link #$code$Loop $code$Loop} method, which
* encapsulates the basic $coding$ loop. A subclass that maintains internal
* state should, additionally, override the {@link #implFlush implFlush} and
* {@link #implReset implReset} methods.
*
* <p> Instances of this class are not safe for use by multiple concurrent
* threads. </p>
*
*
* @author Mark Reinhold
* @author JSR-51 Expert Group
* @since 1.4
*
* @see ByteBuffer
* @see CharBuffer
* @see Charset
* @see Charset$OtherCoder$
*/
public abstract class Charset$Coder$ {
private final Charset charset;
private final float average$ItypesPerOtype$;
private final float max$ItypesPerOtype$;
private $replType$ replacement;
private CodingErrorAction malformedInputAction
= CodingErrorAction.REPORT;
private CodingErrorAction unmappableCharacterAction
= CodingErrorAction.REPORT;
// Internal states
//
private static final int ST_RESET = 0;
private static final int ST_CODING = 1;
private static final int ST_END = 2;
private static final int ST_FLUSHED = 3;
private int state = ST_RESET;
private static String stateNames[]
= { "RESET", "CODING", "CODING_END", "FLUSHED" };
/**
* Initializes a new $coder$. The new $coder$ will have the given
* $otypes-per-itype$ and replacement values.
*
* @param cs
* The charset that created this $coder$
*
* @param average$ItypesPerOtype$
* A positive float value indicating the expected number of
* $otype$s that will be produced for each input $itype$
*
* @param max$ItypesPerOtype$
* A positive float value indicating the maximum number of
* $otype$s that will be produced for each input $itype$
*
* @param replacement
* The initial replacement; must not be {@code null}, must have
* non-zero length, must not be longer than max$ItypesPerOtype$,
* and must be {@linkplain #isLegalReplacement legal}
*
* @throws IllegalArgumentException
* If the preconditions on the parameters do not hold
*/
{#if[encoder]?protected:private}
Charset$Coder$(Charset cs,
float average$ItypesPerOtype$,
float max$ItypesPerOtype$,
$replType$ replacement)
{
this.charset = cs;
if (average$ItypesPerOtype$ <= 0.0f)
throw new IllegalArgumentException("Non-positive "
+ "average$ItypesPerOtype$");
if (max$ItypesPerOtype$ <= 0.0f)
throw new IllegalArgumentException("Non-positive "
+ "max$ItypesPerOtype$");
if (average$ItypesPerOtype$ > max$ItypesPerOtype$)
throw new IllegalArgumentException("average$ItypesPerOtype$"
+ " exceeds "
+ "max$ItypesPerOtype$");
this.replacement = replacement;
this.average$ItypesPerOtype$ = average$ItypesPerOtype$;
this.max$ItypesPerOtype$ = max$ItypesPerOtype$;
replaceWith(replacement);
}
/**
* Initializes a new $coder$. The new $coder$ will have the given
* $otypes-per-itype$ values and its replacement will be the
* $replTypeName$ $defaultReplName$.
*
* @param cs
* The charset that created this $coder$
*
* @param average$ItypesPerOtype$
* A positive float value indicating the expected number of
* $otype$s that will be produced for each input $itype$
*
* @param max$ItypesPerOtype$
* A positive float value indicating the maximum number of
* $otype$s that will be produced for each input $itype$
*
* @throws IllegalArgumentException
* If the preconditions on the parameters do not hold
*/
protected Charset$Coder$(Charset cs,
float average$ItypesPerOtype$,
float max$ItypesPerOtype$)
{
this(cs,
average$ItypesPerOtype$, max$ItypesPerOtype$,
$defaultRepl$);
}
/**
* Returns the charset that created this $coder$.
*
* @return This $coder$'s charset
*/
public final Charset charset() {
return charset;
}
/**
* Returns this $coder$'s replacement value.
*
* @return This $coder$'s current replacement,
* which is never {@code null} and is never empty
*/
public final $replType$ replacement() {
#if[decoder]
return replacement;
#end[decoder]
#if[encoder]
return Arrays.copyOf(replacement, replacement.$replLength$);
#end[encoder]
}
/**
* Changes this $coder$'s replacement value.
*
* <p> This method invokes the {@link #implReplaceWith implReplaceWith}
* method, passing the new replacement, after checking that the new
* replacement is acceptable. </p>
*
* @param newReplacement The new replacement; must not be
* {@code null}, must have non-zero length,
#if[decoder]
* and must not be longer than the value returned by the
* {@link #max$ItypesPerOtype$() max$ItypesPerOtype$} method
#end[decoder]
#if[encoder]
* must not be longer than the value returned by the
* {@link #max$ItypesPerOtype$() max$ItypesPerOtype$} method, and
* must be {@link #isLegalReplacement legal}
#end[encoder]
*
* @return This $coder$
*
* @throws IllegalArgumentException
* If the preconditions on the parameter do not hold
*/
public final Charset$Coder$ replaceWith($replType$ newReplacement) {
if (newReplacement == null)
throw new IllegalArgumentException("Null replacement");
int len = newReplacement.$replLength$;
if (len == 0)
throw new IllegalArgumentException("Empty replacement");
if (len > max$ItypesPerOtype$)
throw new IllegalArgumentException("Replacement too long");
#if[decoder]
this.replacement = newReplacement;
#end[decoder]
#if[encoder]
if (!isLegalReplacement(newReplacement))
throw new IllegalArgumentException("Illegal replacement");
this.replacement = Arrays.copyOf(newReplacement, newReplacement.$replLength$);
#end[encoder]
implReplaceWith(this.replacement);
return this;
}
/**
* Reports a change to this $coder$'s replacement value.
*
* <p> The default implementation of this method does nothing. This method
* should be overridden by $coder$s that require notification of changes to
* the replacement. </p>
*
* @param newReplacement The replacement value
*/
protected void implReplaceWith($replType$ newReplacement) {
}
#if[encoder]
private WeakReference<CharsetDecoder> cachedDecoder = null;
/**
* Tells whether or not the given byte array is a legal replacement value
* for this encoder.
*
* <p> A replacement is legal if, and only if, it is a legal sequence of
* bytes in this encoder's charset; that is, it must be possible to decode
* the replacement into one or more sixteen-bit Unicode characters.
*
* <p> The default implementation of this method is not very efficient; it
* should generally be overridden to improve performance. </p>
*
* @param repl The byte array to be tested
*
* @return {@code true} if, and only if, the given byte array
* is a legal replacement value for this encoder
*/
public boolean isLegalReplacement(byte[] repl) {
WeakReference<CharsetDecoder> wr = cachedDecoder;
CharsetDecoder dec = null;
if ((wr == null) || ((dec = wr.get()) == null)) {
dec = charset().newDecoder();
dec.onMalformedInput(CodingErrorAction.REPORT);
dec.onUnmappableCharacter(CodingErrorAction.REPORT);
cachedDecoder = new WeakReference<CharsetDecoder>(dec);
} else {
dec.reset();
}
ByteBuffer bb = ByteBuffer.wrap(repl);
CharBuffer cb = CharBuffer.allocate((int)(bb.remaining()
* dec.maxCharsPerByte()));
CoderResult cr = dec.decode(bb, cb, true);
return !cr.isError();
}
#end[encoder]
/**
* Returns this $coder$'s current action for malformed-input errors.
*
* @return The current malformed-input action, which is never {@code null}
*/
public CodingErrorAction malformedInputAction() {
return malformedInputAction;
}
/**
* Changes this $coder$'s action for malformed-input errors.
*
* <p> This method invokes the {@link #implOnMalformedInput
* implOnMalformedInput} method, passing the new action. </p>
*
* @param newAction The new action; must not be {@code null}
*
* @return This $coder$
*
* @throws IllegalArgumentException
* If the precondition on the parameter does not hold
*/
public final Charset$Coder$ onMalformedInput(CodingErrorAction newAction) {
if (newAction == null)
throw new IllegalArgumentException("Null action");
malformedInputAction = newAction;
implOnMalformedInput(newAction);
return this;
}
/**
* Reports a change to this $coder$'s malformed-input action.
*
* <p> The default implementation of this method does nothing. This method
* should be overridden by $coder$s that require notification of changes to
* the malformed-input action. </p>
*
* @param newAction The new action
*/
protected void implOnMalformedInput(CodingErrorAction newAction) { }
/**
* Returns this $coder$'s current action for unmappable-character errors.
*
* @return The current unmappable-character action, which is never
* {@code null}
*/
public CodingErrorAction unmappableCharacterAction() {
return unmappableCharacterAction;
}
/**
* Changes this $coder$'s action for unmappable-character errors.
*
* <p> This method invokes the {@link #implOnUnmappableCharacter
* implOnUnmappableCharacter} method, passing the new action. </p>
*
* @param newAction The new action; must not be {@code null}
*
* @return This $coder$
*
* @throws IllegalArgumentException
* If the precondition on the parameter does not hold
*/
public final Charset$Coder$ onUnmappableCharacter(CodingErrorAction
newAction)
{
if (newAction == null)
throw new IllegalArgumentException("Null action");
unmappableCharacterAction = newAction;
implOnUnmappableCharacter(newAction);
return this;
}
/**
* Reports a change to this $coder$'s unmappable-character action.
*
* <p> The default implementation of this method does nothing. This method
* should be overridden by $coder$s that require notification of changes to
* the unmappable-character action. </p>
*
* @param newAction The new action
*/
protected void implOnUnmappableCharacter(CodingErrorAction newAction) { }
/**
* Returns the average number of $otype$s that will be produced for each
* $itype$ of input. This heuristic value may be used to estimate the size
* of the output buffer required for a given input sequence.
*
* @return The average number of $otype$s produced
* per $itype$ of input
*/
public final float average$ItypesPerOtype$() {
return average$ItypesPerOtype$;
}
/**
* Returns the maximum number of $otype$s that will be produced for each
* $itype$ of input. This value may be used to compute the worst-case size
* of the output buffer required for a given input sequence.
*
* @return The maximum number of $otype$s that will be produced per
* $itype$ of input
*/
public final float max$ItypesPerOtype$() {
return max$ItypesPerOtype$;
}
/**
* $Code$s as many $itype$s as possible from the given input buffer,
* writing the results to the given output buffer.
*
* <p> The buffers are read from, and written to, starting at their current
* positions. At most {@link Buffer#remaining in.remaining()} $itype$s
* will be read and at most {@link Buffer#remaining out.remaining()}
* $otype$s will be written. The buffers' positions will be advanced to
* reflect the $itype$s read and the $otype$s written, but their marks and
* limits will not be modified.
*
* <p> In addition to reading $itype$s from the input buffer and writing
* $otype$s to the output buffer, this method returns a {@link CoderResult}
* object to describe its reason for termination:
*
* <ul>
*
* <li><p> {@link CoderResult#UNDERFLOW} indicates that as much of the
* input buffer as possible has been $code$d. If there is no further
* input then the invoker can proceed to the next step of the
* <a href="#steps">$coding$ operation</a>. Otherwise this method
* should be invoked again with further input. </p></li>
*
* <li><p> {@link CoderResult#OVERFLOW} indicates that there is
* insufficient space in the output buffer to $code$ any more $itype$s.
* This method should be invoked again with an output buffer that has
* more {@linkplain Buffer#remaining remaining} $otype$s. This is
* typically done by draining any $code$d $otype$s from the output
* buffer. </p></li>
*
* <li><p> A {@linkplain CoderResult#malformedForLength
* malformed-input} result indicates that a malformed-input
* error has been detected. The malformed $itype$s begin at the input
* buffer's (possibly incremented) position; the number of malformed
* $itype$s may be determined by invoking the result object's {@link
* CoderResult#length() length} method. This case applies only if the
* {@linkplain #onMalformedInput malformed action} of this $coder$
* is {@link CodingErrorAction#REPORT}; otherwise the malformed input
* will be ignored or replaced, as requested. </p></li>
*
* <li><p> An {@linkplain CoderResult#unmappableForLength
* unmappable-character} result indicates that an
* unmappable-character error has been detected. The $itype$s that
* $code$ the unmappable character begin at the input buffer's (possibly
* incremented) position; the number of such $itype$s may be determined
* by invoking the result object's {@link CoderResult#length() length}
* method. This case applies only if the {@linkplain #onUnmappableCharacter
* unmappable action} of this $coder$ is {@link
* CodingErrorAction#REPORT}; otherwise the unmappable character will be
* ignored or replaced, as requested. </p></li>
*
* </ul>
*
* In any case, if this method is to be reinvoked in the same $coding$
* operation then care should be taken to preserve any $itype$s remaining
* in the input buffer so that they are available to the next invocation.
*
* <p> The {@code endOfInput} parameter advises this method as to whether
* the invoker can provide further input beyond that contained in the given
* input buffer. If there is a possibility of providing additional input
* then the invoker should pass {@code false} for this parameter; if there
* is no possibility of providing further input then the invoker should
* pass {@code true}. It is not erroneous, and in fact it is quite
* common, to pass {@code false} in one invocation and later discover that
* no further input was actually available. It is critical, however, that
* the final invocation of this method in a sequence of invocations always
* pass {@code true} so that any remaining un$code$d input will be treated
* as being malformed.
*
* <p> This method works by invoking the {@link #$code$Loop $code$Loop}
* method, interpreting its results, handling error conditions, and
* reinvoking it as necessary. </p>
*
*
* @param in
* The input $itype$ buffer
*
* @param out
* The output $otype$ buffer
*
* @param endOfInput
* {@code true} if, and only if, the invoker can provide no
* additional input $itype$s beyond those in the given buffer
*
* @return A coder-result object describing the reason for termination
*
* @throws IllegalStateException
* If $a$ $coding$ operation is already in progress and the previous
* step was an invocation neither of the {@link #reset reset}
* method, nor of this method with a value of {@code false} for
* the {@code endOfInput} parameter, nor of this method with a
* value of {@code true} for the {@code endOfInput} parameter
* but a return value indicating an incomplete $coding$ operation
*
* @throws CoderMalfunctionError
* If an invocation of the $code$Loop method threw
* an unexpected exception
*/
public final CoderResult $code$($Itype$Buffer in, $Otype$Buffer out,
boolean endOfInput)
{
int newState = endOfInput ? ST_END : ST_CODING;
if ((state != ST_RESET) && (state != ST_CODING)
&& !(endOfInput && (state == ST_END)))
throwIllegalStateException(state, newState);
state = newState;
for (;;) {
CoderResult cr;
try {
cr = $code$Loop(in, out);
} catch (BufferUnderflowException x) {
throw new CoderMalfunctionError(x);
} catch (BufferOverflowException x) {
throw new CoderMalfunctionError(x);
}
if (cr.isOverflow())
return cr;
if (cr.isUnderflow()) {
if (endOfInput && in.hasRemaining()) {
cr = CoderResult.malformedForLength(in.remaining());
// Fall through to malformed-input case
} else {
return cr;
}
}
CodingErrorAction action = null;
if (cr.isMalformed())
action = malformedInputAction;
else if (cr.isUnmappable())
action = unmappableCharacterAction;
else
assert false : cr.toString();
if (action == CodingErrorAction.REPORT)
return cr;
if (action == CodingErrorAction.REPLACE) {
if (out.remaining() < replacement.$replLength$)
return CoderResult.OVERFLOW;
out.put(replacement);
}
if ((action == CodingErrorAction.IGNORE)
|| (action == CodingErrorAction.REPLACE)) {
// Skip erroneous input either way
in.position(in.position() + cr.length());
continue;
}
assert false;
}
}
/**
* Flushes this $coder$.
*
* <p> Some $coder$s maintain internal state and may need to write some
* final $otype$s to the output buffer once the overall input sequence has
* been read.
*
* <p> Any additional output is written to the output buffer beginning at
* its current position. At most {@link Buffer#remaining out.remaining()}
* $otype$s will be written. The buffer's position will be advanced
* appropriately, but its mark and limit will not be modified.
*
* <p> If this method completes successfully then it returns {@link
* CoderResult#UNDERFLOW}. If there is insufficient room in the output
* buffer then it returns {@link CoderResult#OVERFLOW}. If this happens
* then this method must be invoked again, with an output buffer that has
* more room, in order to complete the current <a href="#steps">$coding$
* operation</a>.
*
* <p> If this $coder$ has already been flushed then invoking this method
* has no effect.
*
* <p> This method invokes the {@link #implFlush implFlush} method to
* perform the actual flushing operation. </p>
*
* @param out
* The output $otype$ buffer
*
* @return A coder-result object, either {@link CoderResult#UNDERFLOW} or
* {@link CoderResult#OVERFLOW}
*
* @throws IllegalStateException
* If the previous step of the current $coding$ operation was an
* invocation neither of the {@link #flush flush} method nor of
* the three-argument {@link
* #$code$($Itype$Buffer,$Otype$Buffer,boolean) $code$} method
* with a value of {@code true} for the {@code endOfInput}
* parameter
*/
public final CoderResult flush($Otype$Buffer out) {
if (state == ST_END) {
CoderResult cr = implFlush(out);
if (cr.isUnderflow())
state = ST_FLUSHED;
return cr;
}
if (state != ST_FLUSHED)
throwIllegalStateException(state, ST_FLUSHED);
return CoderResult.UNDERFLOW; // Already flushed
}
/**
* Flushes this $coder$.
*
* <p> The default implementation of this method does nothing, and always
* returns {@link CoderResult#UNDERFLOW}. This method should be overridden
* by $coder$s that may need to write final $otype$s to the output buffer
* once the entire input sequence has been read. </p>
*
* @param out
* The output $otype$ buffer
*
* @return A coder-result object, either {@link CoderResult#UNDERFLOW} or
* {@link CoderResult#OVERFLOW}
*/
protected CoderResult implFlush($Otype$Buffer out) {
return CoderResult.UNDERFLOW;
}
/**
* Resets this $coder$, clearing any internal state.
*
* <p> This method resets charset-independent state and also invokes the
* {@link #implReset() implReset} method in order to perform any
* charset-specific reset actions. </p>
*
* @return This $coder$
*
*/
public final Charset$Coder$ reset() {
implReset();
state = ST_RESET;
return this;
}
/**
* Resets this $coder$, clearing any charset-specific internal state.
*
* <p> The default implementation of this method does nothing. This method
* should be overridden by $coder$s that maintain internal state. </p>
*/
protected void implReset() { }
/**
* $Code$s one or more $itype$s into one or more $otype$s.
*
* <p> This method encapsulates the basic $coding$ loop, $coding$ as many
* $itype$s as possible until it either runs out of input, runs out of room
* in the output buffer, or encounters $a$ $coding$ error. This method is
* invoked by the {@link #$code$ $code$} method, which handles result
* interpretation and error recovery.
*
* <p> The buffers are read from, and written to, starting at their current
* positions. At most {@link Buffer#remaining in.remaining()} $itype$s
* will be read, and at most {@link Buffer#remaining out.remaining()}
* $otype$s will be written. The buffers' positions will be advanced to
* reflect the $itype$s read and the $otype$s written, but their marks and
* limits will not be modified.
*
* <p> This method returns a {@link CoderResult} object to describe its
* reason for termination, in the same manner as the {@link #$code$ $code$}
* method. Most implementations of this method will handle $coding$ errors
* by returning an appropriate result object for interpretation by the
* {@link #$code$ $code$} method. An optimized implementation may instead
* examine the relevant error action and implement that action itself.
*
* <p> An implementation of this method may perform arbitrary lookahead by
* returning {@link CoderResult#UNDERFLOW} until it receives sufficient
* input. </p>
*
* @param in
* The input $itype$ buffer
*
* @param out
* The output $otype$ buffer
*
* @return A coder-result object describing the reason for termination
*/
protected abstract CoderResult $code$Loop($Itype$Buffer in,
$Otype$Buffer out);
/**
* Convenience method that $code$s the remaining content of a single input
* $itype$ buffer into a newly-allocated $otype$ buffer.
*
* <p> This method implements an entire <a href="#steps">$coding$
* operation</a>; that is, it resets this $coder$, then it $code$s the
* $itype$s in the given $itype$ buffer, and finally it flushes this
* $coder$. This method should therefore not be invoked if $a$ $coding$
* operation is already in progress. </p>
*
* @param in
* The input $itype$ buffer
*
* @return A newly-allocated $otype$ buffer containing the result of the
* $coding$ operation. The buffer's position will be zero and its
* limit will follow the last $otype$ written.
*
* @throws IllegalStateException
* If $a$ $coding$ operation is already in progress
*
* @throws MalformedInputException
* If the $itype$ sequence starting at the input buffer's current
* position is $notLegal$ and the current malformed-input action
* is {@link CodingErrorAction#REPORT}
*
* @throws UnmappableCharacterException
* If the $itype$ sequence starting at the input buffer's current
* position cannot be mapped to an equivalent $otype$ sequence and
* the current unmappable-character action is {@link
* CodingErrorAction#REPORT}
*/
public final $Otype$Buffer $code$($Itype$Buffer in)
throws CharacterCodingException
{
int n = (int)(in.remaining() * average$ItypesPerOtype$());
$Otype$Buffer out = $Otype$Buffer.allocate(n);
if ((n == 0) && (in.remaining() == 0))
return out;
reset();
for (;;) {
CoderResult cr = in.hasRemaining() ?
$code$(in, out, true) : CoderResult.UNDERFLOW;
if (cr.isUnderflow())
cr = flush(out);
if (cr.isUnderflow())
break;
if (cr.isOverflow()) {
n = 2*n + 1; // Ensure progress; n might be 0!
$Otype$Buffer o = $Otype$Buffer.allocate(n);
out.flip();
o.put(out);
out = o;
continue;
}
cr.throwException();
}
out.flip();
return out;
}
#if[decoder]
/**
* Tells whether or not this decoder implements an auto-detecting charset.
*
* <p> The default implementation of this method always returns
* {@code false}; it should be overridden by auto-detecting decoders to
* return {@code true}. </p>
*
* @return {@code true} if, and only if, this decoder implements an
* auto-detecting charset
*/
public boolean isAutoDetecting() {
return false;
}
/**
* Tells whether or not this decoder has yet detected a
* charset&nbsp;&nbsp;<i>(optional operation)</i>.
*
* <p> If this decoder implements an auto-detecting charset then at a
* single point during a decoding operation this method may start returning
* {@code true} to indicate that a specific charset has been detected in
* the input byte sequence. Once this occurs, the {@link #detectedCharset
* detectedCharset} method may be invoked to retrieve the detected charset.
*
* <p> That this method returns {@code false} does not imply that no bytes
* have yet been decoded. Some auto-detecting decoders are capable of
* decoding some, or even all, of an input byte sequence without fixing on
* a particular charset.
*
* <p> The default implementation of this method always throws an {@link
* UnsupportedOperationException}; it should be overridden by
* auto-detecting decoders to return {@code true} once the input charset
* has been determined. </p>
*
* @return {@code true} if, and only if, this decoder has detected a
* specific charset
*
* @throws UnsupportedOperationException
* If this decoder does not implement an auto-detecting charset
*/
public boolean isCharsetDetected() {
throw new UnsupportedOperationException();
}
/**
* Retrieves the charset that was detected by this
* decoder&nbsp;&nbsp;<i>(optional operation)</i>.
*
* <p> If this decoder implements an auto-detecting charset then this
* method returns the actual charset once it has been detected. After that
* point, this method returns the same value for the duration of the
* current decoding operation. If not enough input bytes have yet been
* read to determine the actual charset then this method throws an {@link
* IllegalStateException}.
*
* <p> The default implementation of this method always throws an {@link
* UnsupportedOperationException}; it should be overridden by
* auto-detecting decoders to return the appropriate value. </p>
*
* @return The charset detected by this auto-detecting decoder,
* or {@code null} if the charset has not yet been determined
*
* @throws IllegalStateException
* If insufficient bytes have been read to determine a charset
*
* @throws UnsupportedOperationException
* If this decoder does not implement an auto-detecting charset
*/
public Charset detectedCharset() {
throw new UnsupportedOperationException();
}
#end[decoder]
#if[encoder]
private boolean canEncode(CharBuffer cb) {
if (state == ST_FLUSHED)
reset();
else if (state != ST_RESET)
throwIllegalStateException(state, ST_CODING);
CodingErrorAction ma = malformedInputAction();
CodingErrorAction ua = unmappableCharacterAction();
try {
onMalformedInput(CodingErrorAction.REPORT);
onUnmappableCharacter(CodingErrorAction.REPORT);
encode(cb);
} catch (CharacterCodingException x) {
return false;
} finally {
onMalformedInput(ma);
onUnmappableCharacter(ua);
reset();
}
return true;
}
/**
* Tells whether or not this encoder can encode the given character.
*
* <p> This method returns {@code false} if the given character is a
* surrogate character; such characters can be interpreted only when they
* are members of a pair consisting of a high surrogate followed by a low
* surrogate. The {@link #canEncode(java.lang.CharSequence)
* canEncode(CharSequence)} method may be used to test whether or not a
* character sequence can be encoded.
*
* <p> This method may modify this encoder's state; it should therefore not
* be invoked if an <a href="#steps">encoding operation</a> is already in
* progress.
*
* <p> The default implementation of this method is not very efficient; it
* should generally be overridden to improve performance. </p>
*
* @param c
* The given character
*
* @return {@code true} if, and only if, this encoder can encode
* the given character
*
* @throws IllegalStateException
* If $a$ $coding$ operation is already in progress
*/
public boolean canEncode(char c) {
CharBuffer cb = CharBuffer.allocate(1);
cb.put(c);
cb.flip();
return canEncode(cb);
}
/**
* Tells whether or not this encoder can encode the given character
* sequence.
*
* <p> If this method returns {@code false} for a particular character
* sequence then more information about why the sequence cannot be encoded
* may be obtained by performing a full <a href="#steps">encoding
* operation</a>.
*
* <p> This method may modify this encoder's state; it should therefore not
* be invoked if an encoding operation is already in progress.
*
* <p> The default implementation of this method is not very efficient; it
* should generally be overridden to improve performance. </p>
*
* @param cs
* The given character sequence
*
* @return {@code true} if, and only if, this encoder can encode
* the given character without throwing any exceptions and without
* performing any replacements
*
* @throws IllegalStateException
* If $a$ $coding$ operation is already in progress
*/
public boolean canEncode(CharSequence cs) {
CharBuffer cb;
if (cs instanceof CharBuffer)
cb = ((CharBuffer)cs).duplicate();
else
cb = CharBuffer.wrap(cs.toString());
return canEncode(cb);
}
#end[encoder]
private void throwIllegalStateException(int from, int to) {
throw new IllegalStateException("Current state = " + stateNames[from]
+ ", new state = " + stateNames[to]);
}
}

View file

@ -0,0 +1,924 @@
/*
* Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.charset;
import jdk.internal.misc.VM;
import sun.nio.cs.StandardCharsets;
import sun.nio.cs.ThreadLocalCoders;
import sun.security.action.GetPropertyAction;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.spi.CharsetProvider;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* A named mapping between sequences of sixteen-bit Unicode <a
* href="../../lang/Character.html#unicode">code units</a> and sequences of
* bytes. This class defines methods for creating decoders and encoders and
* for retrieving the various names associated with a charset. Instances of
* this class are immutable.
*
* <p> This class also defines static methods for testing whether a particular
* charset is supported, for locating charset instances by name, and for
* constructing a map that contains every charset for which support is
* available in the current Java virtual machine. Support for new charsets can
* be added via the service-provider interface defined in the {@link
* java.nio.charset.spi.CharsetProvider} class.
*
* <p> All of the methods defined in this class are safe for use by multiple
* concurrent threads.
*
*
* <a id="names"></a><a id="charenc"></a>
* <h2>Charset names</h2>
*
* <p> Charsets are named by strings composed of the following characters:
*
* <ul>
*
* <li> The uppercase letters {@code 'A'} through {@code 'Z'}
* (<code>'&#92;u0041'</code>&nbsp;through&nbsp;<code>'&#92;u005a'</code>),
*
* <li> The lowercase letters {@code 'a'} through {@code 'z'}
* (<code>'&#92;u0061'</code>&nbsp;through&nbsp;<code>'&#92;u007a'</code>),
*
* <li> The digits {@code '0'} through {@code '9'}
* (<code>'&#92;u0030'</code>&nbsp;through&nbsp;<code>'&#92;u0039'</code>),
*
* <li> The dash character {@code '-'}
* (<code>'&#92;u002d'</code>,&nbsp;<small>HYPHEN-MINUS</small>),
*
* <li> The plus character {@code '+'}
* (<code>'&#92;u002b'</code>,&nbsp;<small>PLUS SIGN</small>),
*
* <li> The period character {@code '.'}
* (<code>'&#92;u002e'</code>,&nbsp;<small>FULL STOP</small>),
*
* <li> The colon character {@code ':'}
* (<code>'&#92;u003a'</code>,&nbsp;<small>COLON</small>), and
*
* <li> The underscore character {@code '_'}
* (<code>'&#92;u005f'</code>,&nbsp;<small>LOW&nbsp;LINE</small>).
*
* </ul>
*
* A charset name must begin with either a letter or a digit. The empty string
* is not a legal charset name. Charset names are not case-sensitive; that is,
* case is always ignored when comparing charset names. Charset names
* generally follow the conventions documented in <a
* href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278:&nbsp;IANA Charset
* Registration Procedures</i></a>.
*
* <p> Every charset has a <i>canonical name</i> and may also have one or more
* <i>aliases</i>. The canonical name is returned by the {@link #name() name} method
* of this class. Canonical names are, by convention, usually in upper case.
* The aliases of a charset are returned by the {@link #aliases() aliases}
* method.
*
* <p><a id="hn">Some charsets have an <i>historical name</i> that is defined for
* compatibility with previous versions of the Java platform.</a> A charset's
* historical name is either its canonical name or one of its aliases. The
* historical name is returned by the {@code getEncoding()} methods of the
* {@link java.io.InputStreamReader#getEncoding InputStreamReader} and {@link
* java.io.OutputStreamWriter#getEncoding OutputStreamWriter} classes.
*
* <p><a id="iana"> </a>If a charset listed in the <a
* href="http://www.iana.org/assignments/character-sets"><i>IANA Charset
* Registry</i></a> is supported by an implementation of the Java platform then
* its canonical name must be the name listed in the registry. Many charsets
* are given more than one name in the registry, in which case the registry
* identifies one of the names as <i>MIME-preferred</i>. If a charset has more
* than one registry name then its canonical name must be the MIME-preferred
* name and the other names in the registry must be valid aliases. If a
* supported charset is not listed in the IANA registry then its canonical name
* must begin with one of the strings {@code "X-"} or {@code "x-"}.
*
* <p> The IANA charset registry does change over time, and so the canonical
* name and the aliases of a particular charset may also change over time. To
* ensure compatibility it is recommended that no alias ever be removed from a
* charset, and that if the canonical name of a charset is changed then its
* previous canonical name be made into an alias.
*
*
* <h2>Standard charsets</h2>
*
*
*
* <p><a id="standard">Every implementation of the Java platform is required to support the
* following standard charsets.</a> Consult the release documentation for your
* implementation to see if any other charsets are supported. The behavior
* of such optional charsets may differ between implementations.
*
* <blockquote><table class="striped" style="width:80%">
* <caption style="display:none">Description of standard charsets</caption>
* <thead>
* <tr><th scope="col" style="text-align:left">Charset</th><th scope="col" style="text-align:left">Description</th></tr>
* </thead>
* <tbody>
* <tr><th scope="row" style="vertical-align:top">{@code US-ASCII}</th>
* <td>Seven-bit ASCII, a.k.a. {@code ISO646-US},
* a.k.a. the Basic Latin block of the Unicode character set</td></tr>
* <tr><th scope="row" style="vertical-align:top"><code>ISO-8859-1&nbsp;&nbsp;</code></th>
* <td>ISO Latin Alphabet No. 1, a.k.a. {@code ISO-LATIN-1}</td></tr>
* <tr><th scope="row" style="vertical-align:top">{@code UTF-8}</th>
* <td>Eight-bit UCS Transformation Format</td></tr>
* <tr><th scope="row" style="vertical-align:top">{@code UTF-16BE}</th>
* <td>Sixteen-bit UCS Transformation Format,
* big-endian byte&nbsp;order</td></tr>
* <tr><th scope="row" style="vertical-align:top">{@code UTF-16LE}</th>
* <td>Sixteen-bit UCS Transformation Format,
* little-endian byte&nbsp;order</td></tr>
* <tr><th scope="row" style="vertical-align:top">{@code UTF-16}</th>
* <td>Sixteen-bit UCS Transformation Format,
* byte&nbsp;order identified by an optional byte-order mark</td></tr>
* </tbody>
* </table></blockquote>
*
* <p> The {@code UTF-8} charset is specified by <a
* href="http://www.ietf.org/rfc/rfc2279.txt"><i>RFC&nbsp;2279</i></a>; the
* transformation format upon which it is based is specified in
* Amendment&nbsp;2 of ISO&nbsp;10646-1 and is also described in the <a
* href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
* Standard</i></a>.
*
* <p> The {@code UTF-16} charsets are specified by <a
* href="http://www.ietf.org/rfc/rfc2781.txt"><i>RFC&nbsp;2781</i></a>; the
* transformation formats upon which they are based are specified in
* Amendment&nbsp;1 of ISO&nbsp;10646-1 and are also described in the <a
* href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
* Standard</i></a>.
*
* <p> The {@code UTF-16} charsets use sixteen-bit quantities and are
* therefore sensitive to byte order. In these encodings the byte order of a
* stream may be indicated by an initial <i>byte-order mark</i> represented by
* the Unicode character <code>'&#92;uFEFF'</code>. Byte-order marks are handled
* as follows:
*
* <ul>
*
* <li><p> When decoding, the {@code UTF-16BE} and {@code UTF-16LE}
* charsets interpret the initial byte-order marks as a <small>ZERO-WIDTH
* NON-BREAKING SPACE</small>; when encoding, they do not write
* byte-order marks. </p></li>
*
* <li><p> When decoding, the {@code UTF-16} charset interprets the
* byte-order mark at the beginning of the input stream to indicate the
* byte-order of the stream but defaults to big-endian if there is no
* byte-order mark; when encoding, it uses big-endian byte order and writes
* a big-endian byte-order mark. </p></li>
*
* </ul>
*
* In any case, byte order marks occurring after the first element of an
* input sequence are not omitted since the same code is used to represent
* <small>ZERO-WIDTH NON-BREAKING SPACE</small>.
*
* <p> Every instance of the Java virtual machine has a default charset, which
* may or may not be one of the standard charsets. The default charset is
* determined during virtual-machine startup and typically depends upon the
* locale and charset being used by the underlying operating system. </p>
*
* <p>The {@link StandardCharsets} class defines constants for each of the
* standard charsets.
*
* <h2>Terminology</h2>
*
* <p> The name of this class is taken from the terms used in
* <a href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278</i></a>.
* In that document a <i>charset</i> is defined as the combination of
* one or more coded character sets and a character-encoding scheme.
* (This definition is confusing; some other software systems define
* <i>charset</i> as a synonym for <i>coded character set</i>.)
*
* <p> A <i>coded character set</i> is a mapping between a set of abstract
* characters and a set of integers. US-ASCII, ISO&nbsp;8859-1,
* JIS&nbsp;X&nbsp;0201, and Unicode are examples of coded character sets.
*
* <p> Some standards have defined a <i>character set</i> to be simply a
* set of abstract characters without an associated assigned numbering.
* An alphabet is an example of such a character set. However, the subtle
* distinction between <i>character set</i> and <i>coded character set</i>
* is rarely used in practice; the former has become a short form for the
* latter, including in the Java API specification.
*
* <p> A <i>character-encoding scheme</i> is a mapping between one or more
* coded character sets and a set of octet (eight-bit byte) sequences.
* UTF-8, UTF-16, ISO&nbsp;2022, and EUC are examples of
* character-encoding schemes. Encoding schemes are often associated with
* a particular coded character set; UTF-8, for example, is used only to
* encode Unicode. Some schemes, however, are associated with multiple
* coded character sets; EUC, for example, can be used to encode
* characters in a variety of Asian coded character sets.
*
* <p> When a coded character set is used exclusively with a single
* character-encoding scheme then the corresponding charset is usually
* named for the coded character set; otherwise a charset is usually named
* for the encoding scheme and, possibly, the locale of the coded
* character sets that it supports. Hence {@code US-ASCII} is both the
* name of a coded character set and of the charset that encodes it, while
* {@code EUC-JP} is the name of the charset that encodes the
* JIS&nbsp;X&nbsp;0201, JIS&nbsp;X&nbsp;0208, and JIS&nbsp;X&nbsp;0212
* coded character sets for the Japanese language.
*
* <p> The native character encoding of the Java programming language is
* UTF-16. A charset in the Java platform therefore defines a mapping
* between sequences of sixteen-bit UTF-16 code units (that is, sequences
* of chars) and sequences of bytes. </p>
*
*
* @author Mark Reinhold
* @author JSR-51 Expert Group
* @since 1.4
*
* @see CharsetDecoder
* @see CharsetEncoder
* @see java.nio.charset.spi.CharsetProvider
* @see java.lang.Character
*/
public abstract class Charset
implements Comparable<Charset>
{
/* -- Static methods -- */
/**
* Checks that the given string is a legal charset name. </p>
*
* @param s
* A purported charset name
*
* @throws IllegalCharsetNameException
* If the given name is not a legal charset name
*/
private static void checkName(String s) {
int n = s.length();
if (n == 0) {
throw new IllegalCharsetNameException(s);
}
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
if (c == '-' && i != 0) continue;
if (c == '+' && i != 0) continue;
if (c == ':' && i != 0) continue;
if (c == '_' && i != 0) continue;
if (c == '.' && i != 0) continue;
throw new IllegalCharsetNameException(s);
}
}
/* The standard set of charsets */
private static final CharsetProvider standardProvider = new StandardCharsets();
private static final String[] zeroAliases = new String[0];
// Cache of the most-recently-returned charsets,
// along with the names that were used to find them
//
private static volatile Object[] cache1; // "Level 1" cache
private static volatile Object[] cache2; // "Level 2" cache
private static void cache(String charsetName, Charset cs) {
cache2 = cache1;
cache1 = new Object[] { charsetName, cs };
}
// Creates an iterator that walks over the available providers, ignoring
// those whose lookup or instantiation causes a security exception to be
// thrown. Should be invoked with full privileges.
//
private static Iterator<CharsetProvider> providers() {
return new Iterator<>() {
ClassLoader cl = ClassLoader.getSystemClassLoader();
ServiceLoader<CharsetProvider> sl =
ServiceLoader.load(CharsetProvider.class, cl);
Iterator<CharsetProvider> i = sl.iterator();
CharsetProvider next = null;
private boolean getNext() {
while (next == null) {
try {
if (!i.hasNext())
return false;
next = i.next();
} catch (ServiceConfigurationError sce) {
if (sce.getCause() instanceof SecurityException) {
// Ignore security exceptions
continue;
}
throw sce;
}
}
return true;
}
public boolean hasNext() {
return getNext();
}
public CharsetProvider next() {
if (!getNext())
throw new NoSuchElementException();
CharsetProvider n = next;
next = null;
return n;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
// Thread-local gate to prevent recursive provider lookups
private static ThreadLocal<ThreadLocal<?>> gate =
new ThreadLocal<ThreadLocal<?>>();
private static Charset lookupViaProviders(final String charsetName) {
// The runtime startup sequence looks up standard charsets as a
// consequence of the VM's invocation of System.initializeSystemClass
// in order to, e.g., set system properties and encode filenames. At
// that point the application class loader has not been initialized,
// however, so we can't look for providers because doing so will cause
// that loader to be prematurely initialized with incomplete
// information.
//
if (!VM.isBooted())
return null;
if (gate.get() != null)
// Avoid recursive provider lookups
return null;
try {
gate.set(gate);
return AccessController.doPrivileged(
new PrivilegedAction<>() {
public Charset run() {
for (Iterator<CharsetProvider> i = providers();
i.hasNext();) {
CharsetProvider cp = i.next();
Charset cs = cp.charsetForName(charsetName);
if (cs != null)
return cs;
}
return null;
}
});
} finally {
gate.set(null);
}
}
/* The extended set of charsets */
private static class ExtendedProviderHolder {
static final CharsetProvider[] extendedProviders = extendedProviders();
// returns ExtendedProvider, if installed
private static CharsetProvider[] extendedProviders() {
return AccessController.doPrivileged(new PrivilegedAction<>() {
public CharsetProvider[] run() {
CharsetProvider[] cps = new CharsetProvider[1];
int n = 0;
ServiceLoader<CharsetProvider> sl =
ServiceLoader.loadInstalled(CharsetProvider.class);
for (CharsetProvider cp : sl) {
if (n + 1 > cps.length) {
cps = Arrays.copyOf(cps, cps.length << 1);
}
cps[n++] = cp;
}
return n == cps.length ? cps : Arrays.copyOf(cps, n);
}});
}
}
private static Charset lookupExtendedCharset(String charsetName) {
if (!VM.isBooted()) // see lookupViaProviders()
return null;
CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders;
for (CharsetProvider cp : ecps) {
Charset cs = cp.charsetForName(charsetName);
if (cs != null)
return cs;
}
return null;
}
private static Charset lookup(String charsetName) {
if (charsetName == null)
throw new IllegalArgumentException("Null charset name");
Object[] a;
if ((a = cache1) != null && charsetName.equals(a[0]))
return (Charset)a[1];
// We expect most programs to use one Charset repeatedly.
// We convey a hint to this effect to the VM by putting the
// level 1 cache miss code in a separate method.
return lookup2(charsetName);
}
private static Charset lookup2(String charsetName) {
Object[] a;
if ((a = cache2) != null && charsetName.equals(a[0])) {
cache2 = cache1;
cache1 = a;
return (Charset)a[1];
}
Charset cs;
if ((cs = standardProvider.charsetForName(charsetName)) != null ||
(cs = lookupExtendedCharset(charsetName)) != null ||
(cs = lookupViaProviders(charsetName)) != null)
{
cache(charsetName, cs);
return cs;
}
/* Only need to check the name if we didn't find a charset for it */
checkName(charsetName);
return null;
}
/**
* Tells whether the named charset is supported.
*
* @param charsetName
* The name of the requested charset; may be either
* a canonical name or an alias
*
* @return {@code true} if, and only if, support for the named charset
* is available in the current Java virtual machine
*
* @throws IllegalCharsetNameException
* If the given charset name is illegal
*
* @throws IllegalArgumentException
* If the given {@code charsetName} is null
*/
public static boolean isSupported(String charsetName) {
return (lookup(charsetName) != null);
}
/**
* Returns a charset object for the named charset.
*
* @param charsetName
* The name of the requested charset; may be either
* a canonical name or an alias
*
* @return A charset object for the named charset
*
* @throws IllegalCharsetNameException
* If the given charset name is illegal
*
* @throws IllegalArgumentException
* If the given {@code charsetName} is null
*
* @throws UnsupportedCharsetException
* If no support for the named charset is available
* in this instance of the Java virtual machine
*/
public static Charset forName(String charsetName) {
Charset cs = lookup(charsetName);
if (cs != null)
return cs;
throw new UnsupportedCharsetException(charsetName);
}
// Fold charsets from the given iterator into the given map, ignoring
// charsets whose names already have entries in the map.
//
private static void put(Iterator<Charset> i, Map<String,Charset> m) {
while (i.hasNext()) {
Charset cs = i.next();
if (!m.containsKey(cs.name()))
m.put(cs.name(), cs);
}
}
/**
* Constructs a sorted map from canonical charset names to charset objects.
*
* <p> The map returned by this method will have one entry for each charset
* for which support is available in the current Java virtual machine. If
* two or more supported charsets have the same canonical name then the
* resulting map will contain just one of them; which one it will contain
* is not specified. </p>
*
* <p> The invocation of this method, and the subsequent use of the
* resulting map, may cause time-consuming disk or network I/O operations
* to occur. This method is provided for applications that need to
* enumerate all of the available charsets, for example to allow user
* charset selection. This method is not used by the {@link #forName
* forName} method, which instead employs an efficient incremental lookup
* algorithm.
*
* <p> This method may return different results at different times if new
* charset providers are dynamically made available to the current Java
* virtual machine. In the absence of such changes, the charsets returned
* by this method are exactly those that can be retrieved via the {@link
* #forName forName} method. </p>
*
* @return An immutable, case-insensitive map from canonical charset names
* to charset objects
*/
public static SortedMap<String,Charset> availableCharsets() {
return AccessController.doPrivileged(
new PrivilegedAction<>() {
public SortedMap<String,Charset> run() {
TreeMap<String,Charset> m =
new TreeMap<>(
String.CASE_INSENSITIVE_ORDER);
put(standardProvider.charsets(), m);
CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders;
for (CharsetProvider ecp :ecps) {
put(ecp.charsets(), m);
}
for (Iterator<CharsetProvider> i = providers(); i.hasNext();) {
CharsetProvider cp = i.next();
put(cp.charsets(), m);
}
return Collections.unmodifiableSortedMap(m);
}
});
}
private static volatile Charset defaultCharset;
/**
* Returns the default charset of this Java virtual machine.
*
* <p> The default charset is determined during virtual-machine startup and
* typically depends upon the locale and charset of the underlying
* operating system.
*
* @return A charset object for the default charset
*
* @since 1.5
*/
public static Charset defaultCharset() {
if (defaultCharset == null) {
synchronized (Charset.class) {
String csn = GetPropertyAction
.privilegedGetProperty("file.encoding");
Charset cs = lookup(csn);
if (cs != null)
defaultCharset = cs;
else
defaultCharset = sun.nio.cs.UTF_8.INSTANCE;
}
}
return defaultCharset;
}
/* -- Instance fields and methods -- */
private final String name; // tickles a bug in oldjavac
private final String[] aliases; // tickles a bug in oldjavac
private Set<String> aliasSet = null;
/**
* Initializes a new charset with the given canonical name and alias
* set.
*
* @param canonicalName
* The canonical name of this charset
*
* @param aliases
* An array of this charset's aliases, or null if it has no aliases
*
* @throws IllegalCharsetNameException
* If the canonical name or any of the aliases are illegal
*/
protected Charset(String canonicalName, String[] aliases) {
String[] as = Objects.requireNonNullElse(aliases, zeroAliases);
// Skip checks for the standard, built-in Charsets we always load
// during initialization.
if (canonicalName != "ISO-8859-1"
&& canonicalName != "US-ASCII"
&& canonicalName != "UTF-8") {
checkName(canonicalName);
for (int i = 0; i < as.length; i++) {
checkName(as[i]);
}
}
this.name = canonicalName;
this.aliases = as;
}
/**
* Returns this charset's canonical name.
*
* @return The canonical name of this charset
*/
public final String name() {
return name;
}
/**
* Returns a set containing this charset's aliases.
*
* @return An immutable set of this charset's aliases
*/
public final Set<String> aliases() {
if (aliasSet != null)
return aliasSet;
int n = aliases.length;
HashSet<String> hs = new HashSet<>(n);
for (int i = 0; i < n; i++)
hs.add(aliases[i]);
aliasSet = Collections.unmodifiableSet(hs);
return aliasSet;
}
/**
* Returns this charset's human-readable name for the default locale.
*
* <p> The default implementation of this method simply returns this
* charset's canonical name. Concrete subclasses of this class may
* override this method in order to provide a localized display name. </p>
*
* @return The display name of this charset in the default locale
*/
public String displayName() {
return name;
}
/**
* Tells whether or not this charset is registered in the <a
* href="http://www.iana.org/assignments/character-sets">IANA Charset
* Registry</a>.
*
* @return {@code true} if, and only if, this charset is known by its
* implementor to be registered with the IANA
*/
public final boolean isRegistered() {
return !name.startsWith("X-") && !name.startsWith("x-");
}
/**
* Returns this charset's human-readable name for the given locale.
*
* <p> The default implementation of this method simply returns this
* charset's canonical name. Concrete subclasses of this class may
* override this method in order to provide a localized display name. </p>
*
* @param locale
* The locale for which the display name is to be retrieved
*
* @return The display name of this charset in the given locale
*/
public String displayName(Locale locale) {
return name;
}
/**
* Tells whether or not this charset contains the given charset.
*
* <p> A charset <i>C</i> is said to <i>contain</i> a charset <i>D</i> if,
* and only if, every character representable in <i>D</i> is also
* representable in <i>C</i>. If this relationship holds then it is
* guaranteed that every string that can be encoded in <i>D</i> can also be
* encoded in <i>C</i> without performing any replacements.
*
* <p> That <i>C</i> contains <i>D</i> does not imply that each character
* representable in <i>C</i> by a particular byte sequence is represented
* in <i>D</i> by the same byte sequence, although sometimes this is the
* case.
*
* <p> Every charset contains itself.
*
* <p> This method computes an approximation of the containment relation:
* If it returns {@code true} then the given charset is known to be
* contained by this charset; if it returns {@code false}, however, then
* it is not necessarily the case that the given charset is not contained
* in this charset.
*
* @param cs
* The given charset
*
* @return {@code true} if the given charset is contained in this charset
*/
public abstract boolean contains(Charset cs);
/**
* Constructs a new decoder for this charset.
*
* @return A new decoder for this charset
*/
public abstract CharsetDecoder newDecoder();
/**
* Constructs a new encoder for this charset.
*
* @return A new encoder for this charset
*
* @throws UnsupportedOperationException
* If this charset does not support encoding
*/
public abstract CharsetEncoder newEncoder();
/**
* Tells whether or not this charset supports encoding.
*
* <p> Nearly all charsets support encoding. The primary exceptions are
* special-purpose <i>auto-detect</i> charsets whose decoders can determine
* which of several possible encoding schemes is in use by examining the
* input byte sequence. Such charsets do not support encoding because
* there is no way to determine which encoding should be used on output.
* Implementations of such charsets should override this method to return
* {@code false}. </p>
*
* @return {@code true} if, and only if, this charset supports encoding
*/
public boolean canEncode() {
return true;
}
/**
* Convenience method that decodes bytes in this charset into Unicode
* characters.
*
* <p> An invocation of this method upon a charset {@code cs} returns the
* same result as the expression
*
* <pre>
* cs.newDecoder()
* .onMalformedInput(CodingErrorAction.REPLACE)
* .onUnmappableCharacter(CodingErrorAction.REPLACE)
* .decode(bb); </pre>
*
* except that it is potentially more efficient because it can cache
* decoders between successive invocations.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement byte array. In order
* to detect such sequences, use the {@link
* CharsetDecoder#decode(java.nio.ByteBuffer)} method directly. </p>
*
* @param bb The byte buffer to be decoded
*
* @return A char buffer containing the decoded characters
*/
public final CharBuffer decode(ByteBuffer bb) {
try {
return ThreadLocalCoders.decoderFor(this)
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.decode(bb);
} catch (CharacterCodingException x) {
throw new Error(x); // Can't happen
}
}
/**
* Convenience method that encodes Unicode characters into bytes in this
* charset.
*
* <p> An invocation of this method upon a charset {@code cs} returns the
* same result as the expression
*
* <pre>
* cs.newEncoder()
* .onMalformedInput(CodingErrorAction.REPLACE)
* .onUnmappableCharacter(CodingErrorAction.REPLACE)
* .encode(bb); </pre>
*
* except that it is potentially more efficient because it can cache
* encoders between successive invocations.
*
* <p> This method always replaces malformed-input and unmappable-character
* sequences with this charset's default replacement string. In order to
* detect such sequences, use the {@link
* CharsetEncoder#encode(java.nio.CharBuffer)} method directly. </p>
*
* @param cb The char buffer to be encoded
*
* @return A byte buffer containing the encoded characters
*/
public final ByteBuffer encode(CharBuffer cb) {
try {
return ThreadLocalCoders.encoderFor(this)
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE)
.encode(cb);
} catch (CharacterCodingException x) {
throw new Error(x); // Can't happen
}
}
/**
* Convenience method that encodes a string into bytes in this charset.
*
* <p> An invocation of this method upon a charset {@code cs} returns the
* same result as the expression
*
* <pre>
* cs.encode(CharBuffer.wrap(s)); </pre>
*
* @param str The string to be encoded
*
* @return A byte buffer containing the encoded characters
*/
public final ByteBuffer encode(String str) {
return encode(CharBuffer.wrap(str));
}
/**
* Compares this charset to another.
*
* <p> Charsets are ordered by their canonical names, without regard to
* case. </p>
*
* @param that
* The charset to which this charset is to be compared
*
* @return A negative integer, zero, or a positive integer as this charset
* is less than, equal to, or greater than the specified charset
*/
public final int compareTo(Charset that) {
return (name().compareToIgnoreCase(that.name()));
}
/**
* Computes a hashcode for this charset.
*
* @return An integer hashcode
*/
public final int hashCode() {
return name().hashCode();
}
/**
* Tells whether or not this object is equal to another.
*
* <p> Two charsets are equal if, and only if, they have the same canonical
* names. A charset is never equal to any other type of object. </p>
*
* @return {@code true} if, and only if, this charset is equal to the
* given object
*/
public final boolean equals(Object ob) {
if (!(ob instanceof Charset))
return false;
if (this == ob)
return true;
return name.equals(((Charset)ob).name());
}
/**
* Returns a string describing this charset.
*
* @return A string describing this charset
*/
public final String toString() {
return name();
}
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2001, 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.charset;
/**
* Error thrown when the {@link CharsetDecoder#decodeLoop decodeLoop} method of
* a {@link CharsetDecoder}, or the {@link CharsetEncoder#encodeLoop
* encodeLoop} method of a {@link CharsetEncoder}, throws an unexpected
* exception.
*
* @since 1.4
*/
public class CoderMalfunctionError
extends Error
{
private static final long serialVersionUID = -1151412348057794301L;
/**
* Initializes an instance of this class.
*
* @param cause
* The unexpected exception that was thrown
*/
public CoderMalfunctionError(Exception cause) {
super(cause);
}
}

View file

@ -0,0 +1,288 @@
/*
* Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.charset;
import java.lang.ref.WeakReference;
import java.nio.*;
import java.util.Map;
import java.util.HashMap;
/**
* A description of the result state of a coder.
*
* <p> A charset coder, that is, either a decoder or an encoder, consumes bytes
* (or characters) from an input buffer, translates them, and writes the
* resulting characters (or bytes) to an output buffer. A coding process
* terminates for one of four categories of reasons, which are described by
* instances of this class:
*
* <ul>
*
* <li><p> <i>Underflow</i> is reported when there is no more input to be
* processed, or there is insufficient input and additional input is
* required. This condition is represented by the unique result object
* {@link #UNDERFLOW}, whose {@link #isUnderflow() isUnderflow} method
* returns {@code true}. </p></li>
*
* <li><p> <i>Overflow</i> is reported when there is insufficient room
* remaining in the output buffer. This condition is represented by the
* unique result object {@link #OVERFLOW}, whose {@link #isOverflow()
* isOverflow} method returns {@code true}. </p></li>
*
* <li><p> A <i>malformed-input error</i> is reported when a sequence of
* input units is not well-formed. Such errors are described by instances of
* this class whose {@link #isMalformed() isMalformed} method returns
* {@code true} and whose {@link #length() length} method returns the length
* of the malformed sequence. There is one unique instance of this class for
* all malformed-input errors of a given length. </p></li>
*
* <li><p> An <i>unmappable-character error</i> is reported when a sequence
* of input units denotes a character that cannot be represented in the
* output charset. Such errors are described by instances of this class
* whose {@link #isUnmappable() isUnmappable} method returns {@code true} and
* whose {@link #length() length} method returns the length of the input
* sequence denoting the unmappable character. There is one unique instance
* of this class for all unmappable-character errors of a given length.
* </p></li>
*
* </ul>
*
* <p> For convenience, the {@link #isError() isError} method returns {@code true}
* for result objects that describe malformed-input and unmappable-character
* errors but {@code false} for those that describe underflow or overflow
* conditions. </p>
*
*
* @author Mark Reinhold
* @author JSR-51 Expert Group
* @since 1.4
*/
public class CoderResult {
private static final int CR_UNDERFLOW = 0;
private static final int CR_OVERFLOW = 1;
private static final int CR_ERROR_MIN = 2;
private static final int CR_MALFORMED = 2;
private static final int CR_UNMAPPABLE = 3;
private static final String[] names
= { "UNDERFLOW", "OVERFLOW", "MALFORMED", "UNMAPPABLE" };
private final int type;
private final int length;
private CoderResult(int type, int length) {
this.type = type;
this.length = length;
}
/**
* Returns a string describing this coder result.
*
* @return A descriptive string
*/
public String toString() {
String nm = names[type];
return isError() ? nm + "[" + length + "]" : nm;
}
/**
* Tells whether or not this object describes an underflow condition.
*
* @return {@code true} if, and only if, this object denotes underflow
*/
public boolean isUnderflow() {
return (type == CR_UNDERFLOW);
}
/**
* Tells whether or not this object describes an overflow condition.
*
* @return {@code true} if, and only if, this object denotes overflow
*/
public boolean isOverflow() {
return (type == CR_OVERFLOW);
}
/**
* Tells whether or not this object describes an error condition.
*
* @return {@code true} if, and only if, this object denotes either a
* malformed-input error or an unmappable-character error
*/
public boolean isError() {
return (type >= CR_ERROR_MIN);
}
/**
* Tells whether or not this object describes a malformed-input error.
*
* @return {@code true} if, and only if, this object denotes a
* malformed-input error
*/
public boolean isMalformed() {
return (type == CR_MALFORMED);
}
/**
* Tells whether or not this object describes an unmappable-character
* error.
*
* @return {@code true} if, and only if, this object denotes an
* unmappable-character error
*/
public boolean isUnmappable() {
return (type == CR_UNMAPPABLE);
}
/**
* Returns the length of the erroneous input described by this
* object&nbsp;&nbsp;<i>(optional operation)</i>.
*
* @return The length of the erroneous input, a positive integer
*
* @throws UnsupportedOperationException
* If this object does not describe an error condition, that is,
* if the {@link #isError() isError} does not return {@code true}
*/
public int length() {
if (!isError())
throw new UnsupportedOperationException();
return length;
}
/**
* Result object indicating underflow, meaning that either the input buffer
* has been completely consumed or, if the input buffer is not yet empty,
* that additional input is required.
*/
public static final CoderResult UNDERFLOW
= new CoderResult(CR_UNDERFLOW, 0);
/**
* Result object indicating overflow, meaning that there is insufficient
* room in the output buffer.
*/
public static final CoderResult OVERFLOW
= new CoderResult(CR_OVERFLOW, 0);
private abstract static class Cache {
private Map<Integer,WeakReference<CoderResult>> cache = null;
protected abstract CoderResult create(int len);
private synchronized CoderResult get(int len) {
if (len <= 0)
throw new IllegalArgumentException("Non-positive length");
Integer k = len;
WeakReference<CoderResult> w;
CoderResult e = null;
if (cache == null) {
cache = new HashMap<>();
} else if ((w = cache.get(k)) != null) {
e = w.get();
}
if (e == null) {
e = create(len);
cache.put(k, new WeakReference<>(e));
}
return e;
}
}
private static Cache malformedCache
= new Cache() {
public CoderResult create(int len) {
return new CoderResult(CR_MALFORMED, len);
}};
/**
* Static factory method that returns the unique object describing a
* malformed-input error of the given length.
*
* @param length
* The given length
*
* @return The requested coder-result object
*/
public static CoderResult malformedForLength(int length) {
return malformedCache.get(length);
}
private static Cache unmappableCache
= new Cache() {
public CoderResult create(int len) {
return new CoderResult(CR_UNMAPPABLE, len);
}};
/**
* Static factory method that returns the unique result object describing
* an unmappable-character error of the given length.
*
* @param length
* The given length
*
* @return The requested coder-result object
*/
public static CoderResult unmappableForLength(int length) {
return unmappableCache.get(length);
}
/**
* Throws an exception appropriate to the result described by this object.
*
* @throws BufferUnderflowException
* If this object is {@link #UNDERFLOW}
*
* @throws BufferOverflowException
* If this object is {@link #OVERFLOW}
*
* @throws MalformedInputException
* If this object represents a malformed-input error; the
* exception's length value will be that of this object
*
* @throws UnmappableCharacterException
* If this object represents an unmappable-character error; the
* exceptions length value will be that of this object
*/
public void throwException()
throws CharacterCodingException
{
switch (type) {
case CR_UNDERFLOW: throw new BufferUnderflowException();
case CR_OVERFLOW: throw new BufferOverflowException();
case CR_MALFORMED: throw new MalformedInputException(length);
case CR_UNMAPPABLE: throw new UnmappableCharacterException(length);
default:
assert false;
}
}
}

View file

@ -0,0 +1,84 @@
/*
* Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.charset;
/**
* A typesafe enumeration for coding-error actions.
*
* <p> Instances of this class are used to specify how malformed-input and
* unmappable-character errors are to be handled by charset <a
* href="CharsetDecoder.html#cae">decoders</a> and <a
* href="CharsetEncoder.html#cae">encoders</a>. </p>
*
*
* @author Mark Reinhold
* @author JSR-51 Expert Group
* @since 1.4
*/
public class CodingErrorAction {
private String name;
private CodingErrorAction(String name) {
this.name = name;
}
/**
* Action indicating that a coding error is to be handled by dropping the
* erroneous input and resuming the coding operation.
*/
public static final CodingErrorAction IGNORE
= new CodingErrorAction("IGNORE");
/**
* Action indicating that a coding error is to be handled by dropping the
* erroneous input, appending the coder's replacement value to the output
* buffer, and resuming the coding operation.
*/
public static final CodingErrorAction REPLACE
= new CodingErrorAction("REPLACE");
/**
* Action indicating that a coding error is to be reported, either by
* returning a {@link CoderResult} object or by throwing a {@link
* CharacterCodingException}, whichever is appropriate for the method
* implementing the coding process.
*/
public static final CodingErrorAction REPORT
= new CodingErrorAction("REPORT");
/**
* Returns a string describing this action.
*
* @return A descriptive string
*/
public String toString() {
return name;
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.charset;
/**
* Checked exception thrown when an input byte sequence is not legal for given
* charset, or an input character sequence is not a legal sixteen-bit Unicode
* sequence.
*
* @since 1.4
*/
public class MalformedInputException
extends CharacterCodingException
{
private static final long serialVersionUID = -3438823399834806194L;
private int inputLength;
/**
* Constructs an {@code MalformedInputException} with the given
* length.
* @param inputLength the length of the input
*/
public MalformedInputException(int inputLength) {
this.inputLength = inputLength;
}
/**
* Returns the length of the input.
* @return the length of the input
*/
public int getInputLength() {
return inputLength;
}
/**
* Returns the message.
* @return the message
*/
public String getMessage() {
return "Input length = " + inputLength;
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.charset;
/**
* Constant definitions for the standard {@link Charset Charsets}. These
* charsets are guaranteed to be available on every implementation of the Java
* platform.
*
* @see <a href="Charset.html#standard">Standard Charsets</a>
* @since 1.7
*/
public final class StandardCharsets {
private StandardCharsets() {
throw new AssertionError("No java.nio.charset.StandardCharsets instances for you!");
}
/**
* Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the
* Unicode character set
*/
public static final Charset US_ASCII = sun.nio.cs.US_ASCII.INSTANCE;
/**
* ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
*/
public static final Charset ISO_8859_1 = sun.nio.cs.ISO_8859_1.INSTANCE;
/**
* Eight-bit UCS Transformation Format
*/
public static final Charset UTF_8 = sun.nio.cs.UTF_8.INSTANCE;
/**
* Sixteen-bit UCS Transformation Format, big-endian byte order
*/
public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
/**
* Sixteen-bit UCS Transformation Format, little-endian byte order
*/
public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
/**
* Sixteen-bit UCS Transformation Format, byte order identified by an
* optional byte-order mark
*/
public static final Charset UTF_16 = Charset.forName("UTF-16");
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.charset;
/**
* Checked exception thrown when an input character (or byte) sequence
* is valid but cannot be mapped to an output byte (or character)
* sequence.
*
* @since 1.4
*/
public class UnmappableCharacterException
extends CharacterCodingException
{
private static final long serialVersionUID = -7026962371537706123L;
private int inputLength;
/**
* Constructs an {@code UnmappableCharacterException} with the
* given length.
* @param inputLength the length of the input
*/
public UnmappableCharacterException(int inputLength) {
this.inputLength = inputLength;
}
/**
* Returns the length of the input.
* @return the length of the input
*/
public int getInputLength() {
return inputLength;
}
/**
* Returns the message.
* @return the message
*/
public String getMessage() {
return "Input length = " + inputLength;
}
}

View file

@ -0,0 +1,53 @@
#
# Copyright (c) 2000, 2007, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# Generated exception classes for java.nio.charset
SINCE=1.4
PACKAGE=java.nio.charset
# This year should only change if the generated source is modified.
COPYRIGHT_YEARS="2000, 2007,"
SUPER=java.io.IOException
gen CharacterCodingException "
* Checked exception thrown when a character encoding
* or decoding error occurs." \
8421532232154627783L
SUPER=IllegalArgumentException
gen IllegalCharsetNameException "
* Unchecked exception thrown when a string that is not a
* <a href="Charset.html#names">legal charset name</a> is used as such." \
1457525358470002989L \
String charsetName CharsetName "illegal charset name"
gen UnsupportedCharsetException "
* Unchecked exception thrown when no support is available
* for a requested charset." \
1490765524727386367L \
String charsetName CharsetName "name of the unsupported charset"

View file

@ -0,0 +1,95 @@
/*
* Copyright (c) 2001, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Defines charsets, decoders, and encoders, for translating between
* bytes and Unicode characters.
*
* <table class="striped" style="margin-left:2em; text-align:left">
* <caption style="display:none">Summary of charsets, decoders, and encoders in this package</caption>
* <thead>
* <tr><th scope="col">Class name</th>
* <th scope="col">Description
* </thead>
* <tbody>
* <tr><th scope="row">{@link java.nio.charset.Charset}</th>
* <td>A named mapping between characters and bytes</td></tr>
* <tr><th scope="row">{@link java.nio.charset.CharsetDecoder}</th>
* <td>Decodes bytes into characters</td></tr>
* <tr><th scope="row">{@link java.nio.charset.CharsetEncoder}</th>
* <td>Encodes characters into bytes</td></tr>
* <tr><th scope="row">{@link java.nio.charset.CoderResult}</th>
* <td>Describes coder results</td></tr>
* <tr><th scope="row">{@link java.nio.charset.CodingErrorAction}</th>
* <td>Describes actions to take when coding errors are detected</td></tr>
* </tbody>
* </table>
*
* <p> A <i>charset</i> is named mapping between sequences of
* sixteen-bit Unicode characters and sequences of bytes, in the sense
* defined in <a
* href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278</i></a>.
* A <i>decoder</i> is an engine which transforms bytes in a specific
* charset into characters, and an <i>encoder</i> is an engine which
* transforms characters into bytes. Encoders and decoders operate on
* byte and character buffers. They are collectively referred to as
* <i>coders</i>.
*
* <p> The {@link java.nio.charset.Charset} class defines methods for
* creating coders for a given charset and for retrieving the various
* names associated with a charset. It also defines static methods
* for testing whether a particular charset is supported, for locating
* charset instances by name, and for constructing a map that contains
* every charset for which support is available in the current Java
* virtual machine.
*
* <p> Most users will not use these classes directly; instead they
* will use the existing charset-related constructors and methods in
* the {@link java.lang.String} class, together with the existing
* {@link java.io.InputStreamReader} and {@link
* java.io.OutputStreamWriter} classes, all of whose implementations
* have been reworked to make use of the charset facilities defined in
* this package. A small number of changes have been made to the
* {@link java.io.InputStreamReader} and {@link
* java.io.OutputStreamWriter} classes in order to allow explicit
* charset objects to be specified in the construction of instances of
* those classes.
*
* <p> Support for new charsets can be made available via the
* interface defined in the {@link
* java.nio.charset.spi.CharsetProvider} class in the {@link
* java.nio.charset.spi} package.
*
* <p> Unless otherwise noted, passing a {@code null} argument to a
* constructor or method in any class or interface in this package
* will cause a {@link java.lang.NullPointerException
* NullPointerException} to be thrown.
*
*
* @since 1.4
* @author Mark Reinhold
* @author JSR-51 Expert Group
*/
package java.nio.charset;

View file

@ -0,0 +1,115 @@
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.nio.charset.spi;
import java.nio.charset.Charset;
import java.util.Iterator;
/**
* Charset service-provider class.
*
* <p> A charset provider is a concrete subclass of this class that has a
* zero-argument constructor and some number of associated charset
* implementation classes. Charset providers may be installed in an instance
* of the Java platform as extensions. Providers may also be made available by
* adding them to the applet or application class path or by some other
* platform-specific means. Charset providers are looked up via the current
* thread's {@link java.lang.Thread#getContextClassLoader() context class
* loader}.
*
* <p> A charset provider identifies itself with a provider-configuration file
* named {@code java.nio.charset.spi.CharsetProvider} in the resource
* directory {@code META-INF/services}. The file should contain a list of
* fully-qualified concrete charset-provider class names, one per line. A line
* is terminated by any one of a line feed ({@code '\n'}), a carriage return
* ({@code '\r'}), or a carriage return followed immediately by a line feed.
* Space and tab characters surrounding each name, as well as blank lines, are
* ignored. The comment character is {@code '#'} (<code>'&#92;u0023'</code>); on
* each line all characters following the first comment character are ignored.
* The file must be encoded in UTF-8.
*
* <p> If a particular concrete charset provider class is named in more than
* one configuration file, or is named in the same configuration file more than
* once, then the duplicates will be ignored. The configuration file naming a
* particular provider need not be in the same jar file or other distribution
* unit as the provider itself. The provider must be accessible from the same
* class loader that was initially queried to locate the configuration file;
* this is not necessarily the class loader that loaded the file. </p>
*
*
* @author Mark Reinhold
* @author JSR-51 Expert Group
* @since 1.4
*
* @see java.nio.charset.Charset
*/
public abstract class CharsetProvider {
private static Void checkPermission() {
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkPermission(new RuntimePermission("charsetProvider"));
return null;
}
private CharsetProvider(Void ignore) { }
/**
* Initializes a new charset provider.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link RuntimePermission}{@code ("charsetProvider")}
*/
protected CharsetProvider() {
this(checkPermission());
}
/**
* Creates an iterator that iterates over the charsets supported by this
* provider. This method is used in the implementation of the {@link
* java.nio.charset.Charset#availableCharsets Charset.availableCharsets}
* method.
*
* @return The new iterator
*/
public abstract Iterator<Charset> charsets();
/**
* Retrieves a charset for the given charset name.
*
* @param charsetName
* The name of the requested charset; may be either
* a canonical name or an alias
*
* @return A charset object for the named charset,
* or {@code null} if the named charset
* is not supported by this provider
*/
public abstract Charset charsetForName(String charsetName);
}

View file

@ -0,0 +1,41 @@
/*
* Copyright (c) 2001, 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* Service-provider classes for the {@link java.nio.charset} package.
*
* <p> Only developers who are defining new charsets should need to
* make direct use of this package. </p>
*
* <p> Unless otherwise noted, passing a {@code null} argument to a
* constructor or method in any class or interface in this package
* will cause a {@link java.lang.NullPointerException
* NullPointerException} to be thrown.
*
* @since 1.4
* @author Mark Reinhold
* @author JSR-51 Expert Group
*/
package java.nio.charset.spi;