Search in sources :

Example 86 with CoderResult

use of java.nio.charset.CoderResult in project spring-framework by spring-projects.

the class DataBuffer method write.

/**
 * Write the given {@code CharSequence} using the given {@code Charset},
 * starting at the current writing position.
 * @param charSequence the char sequence to write into this buffer
 * @param charset the charset to encode the char sequence with
 * @return this buffer
 * @since 5.1.4
 */
default DataBuffer write(CharSequence charSequence, Charset charset) {
    Assert.notNull(charSequence, "CharSequence must not be null");
    Assert.notNull(charset, "Charset must not be null");
    if (charSequence.length() != 0) {
        CharsetEncoder charsetEncoder = charset.newEncoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE);
        CharBuffer inBuffer = CharBuffer.wrap(charSequence);
        int estimatedSize = (int) (inBuffer.remaining() * charsetEncoder.averageBytesPerChar());
        ByteBuffer outBuffer = ensureCapacity(estimatedSize).asByteBuffer(writePosition(), writableByteCount());
        while (true) {
            CoderResult cr = (inBuffer.hasRemaining() ? charsetEncoder.encode(inBuffer, outBuffer, true) : CoderResult.UNDERFLOW);
            if (cr.isUnderflow()) {
                cr = charsetEncoder.flush(outBuffer);
            }
            if (cr.isUnderflow()) {
                break;
            }
            if (cr.isOverflow()) {
                writePosition(writePosition() + outBuffer.position());
                int maximumSize = (int) (inBuffer.remaining() * charsetEncoder.maxBytesPerChar());
                ensureCapacity(maximumSize);
                outBuffer = asByteBuffer(writePosition(), writableByteCount());
            }
        }
        writePosition(writePosition() + outBuffer.position());
    }
    return this;
}
Also used : CharBuffer(java.nio.CharBuffer) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer) CoderResult(java.nio.charset.CoderResult)

Example 87 with CoderResult

use of java.nio.charset.CoderResult in project druid by druid-io.

the class StringInputRowParser method buildStringKeyMap.

public Map<String, Object> buildStringKeyMap(ByteBuffer input) {
    int payloadSize = input.remaining();
    if (chars == null || chars.remaining() < payloadSize) {
        chars = CharBuffer.allocate(payloadSize);
    }
    final CoderResult coderResult = charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).decode(input, chars, true);
    Map<String, Object> theMap;
    if (coderResult.isUnderflow()) {
        chars.flip();
        try {
            theMap = parseString(chars.toString());
        } finally {
            chars.clear();
        }
    } else {
        throw new ParseException(chars.toString(), "Failed with CoderResult[%s]", coderResult);
    }
    return theMap;
}
Also used : ParseException(org.apache.druid.java.util.common.parsers.ParseException) CoderResult(java.nio.charset.CoderResult)

Example 88 with CoderResult

use of java.nio.charset.CoderResult in project randomizedtesting by randomizedtesting.

the class WriterOutputStream method processInput.

/**
 * Decode the contents of the input ByteBuffer into a CharBuffer.
 *
 * @param endOfInput indicates end of input
 * @throws IOException if an I/O error occurs
 */
private void processInput(boolean endOfInput) throws IOException {
    // Prepare decoderIn for reading
    decoderIn.flip();
    CoderResult coderResult;
    while (true) {
        coderResult = decoder.decode(decoderIn, decoderOut, endOfInput);
        if (coderResult.isOverflow()) {
            flushOutput();
        } else if (coderResult.isUnderflow()) {
            break;
        } else {
            // so we should not get here.
            throw new IOException("Unexpected coder result");
        }
    }
    // Discard the bytes that have been read
    decoderIn.compact();
}
Also used : IOException(java.io.IOException) CoderResult(java.nio.charset.CoderResult)

Example 89 with CoderResult

use of java.nio.charset.CoderResult in project undertow by undertow-io.

the class ServletPrintWriter method close.

public void close() {
    if (outputStream.getServletRequestContext().getOriginalRequest().getDispatcherType() == DispatcherType.INCLUDE) {
        return;
    }
    if (closed) {
        return;
    }
    closed = true;
    try {
        boolean done = false;
        CharBuffer buffer;
        if (underflow == null) {
            buffer = CharBuffer.wrap(EMPTY_CHAR);
        } else {
            buffer = CharBuffer.wrap(underflow);
            underflow = null;
        }
        if (charsetEncoder != null) {
            do {
                ByteBuffer out = outputStream.underlyingBuffer();
                if (out == null) {
                    // servlet output stream has already been closed
                    error = true;
                    return;
                }
                CoderResult result = charsetEncoder.encode(buffer, out, true);
                if (result.isOverflow()) {
                    outputStream.flushInternal();
                    if (out.remaining() == 0) {
                        outputStream.close();
                        error = true;
                        return;
                    }
                } else {
                    done = true;
                }
            } while (!done);
        }
        outputStream.close();
    } catch (IOException e) {
        error = true;
    }
}
Also used : CharBuffer(java.nio.CharBuffer) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) CoderResult(java.nio.charset.CoderResult)

Example 90 with CoderResult

use of java.nio.charset.CoderResult in project hs4j by killme2008.

the class AbstractIoBuffer method getPrefixedString.

/**
 * Reads a string which has a length field before the actual encoded string,
 * using the specified <code>decoder</code> and returns it.
 *
 * @param prefixLength
 *            the length of the length field (1, 2, or 4)
 * @param decoder
 *            the decoder to use for decoding the string
 * @return the prefixed string
 * @throws CharacterCodingException
 *             when decoding fails
 * @throws BufferUnderflowException
 *             when there is not enough data available
 */
@Override
public String getPrefixedString(int prefixLength, CharsetDecoder decoder) throws CharacterCodingException {
    if (!prefixedDataAvailable(prefixLength)) {
        throw new BufferUnderflowException();
    }
    int fieldSize = 0;
    switch(prefixLength) {
        case 1:
            fieldSize = getUnsigned();
            break;
        case 2:
            fieldSize = getUnsignedShort();
            break;
        case 4:
            fieldSize = getInt();
            break;
    }
    if (fieldSize == 0) {
        return "";
    }
    boolean utf16 = decoder.charset().name().startsWith("UTF-16");
    if (utf16 && (fieldSize & 1) != 0) {
        throw new BufferDataException("fieldSize is not even for a UTF-16 string.");
    }
    int oldLimit = limit();
    int end = position() + fieldSize;
    if (oldLimit < end) {
        throw new BufferUnderflowException();
    }
    limit(end);
    decoder.reset();
    int expectedLength = (int) (remaining() * decoder.averageCharsPerByte()) + 1;
    CharBuffer out = CharBuffer.allocate(expectedLength);
    for (; ; ) {
        CoderResult cr;
        if (hasRemaining()) {
            cr = decoder.decode(buf(), out, true);
        } else {
            cr = decoder.flush(out);
        }
        if (cr.isUnderflow()) {
            break;
        }
        if (cr.isOverflow()) {
            CharBuffer o = CharBuffer.allocate(out.capacity() + expectedLength);
            out.flip();
            o.put(out);
            out = o;
            continue;
        }
        cr.throwException();
    }
    limit(oldLimit);
    position(end);
    return out.flip().toString();
}
Also used : CharBuffer(java.nio.CharBuffer) BufferUnderflowException(java.nio.BufferUnderflowException) CoderResult(java.nio.charset.CoderResult)

Aggregations

CoderResult (java.nio.charset.CoderResult)188 CharBuffer (java.nio.CharBuffer)121 ByteBuffer (java.nio.ByteBuffer)70 CharsetDecoder (java.nio.charset.CharsetDecoder)40 IOException (java.io.IOException)33 CharacterCodingException (java.nio.charset.CharacterCodingException)30 CharsetEncoder (java.nio.charset.CharsetEncoder)25 Charset (java.nio.charset.Charset)15 ArrayDecoder (sun.nio.cs.ArrayDecoder)7 ArrayEncoder (sun.nio.cs.ArrayEncoder)7 JSONException (com.alibaba.fastjson.JSONException)3 BufferUnderflowException (java.nio.BufferUnderflowException)3 CloseReason (jakarta.websocket.CloseReason)2 UncheckedIOException (java.io.UncheckedIOException)2 BufferOverflowException (java.nio.BufferOverflowException)2 IllegalCharsetNameException (java.nio.charset.IllegalCharsetNameException)2 UnmappableCharacterException (java.nio.charset.UnmappableCharacterException)2 UnsupportedCharsetException (java.nio.charset.UnsupportedCharsetException)2 CloseReason (javax.websocket.CloseReason)2 InvalidConfigurationException (org.bukkit.configuration.InvalidConfigurationException)2