Search in sources :

Example 71 with CoderResult

use of java.nio.charset.CoderResult in project tomcat70 by apache.

the class C2BConverter method convert.

/**
 * Convert the given characters to bytes.
 *
 * @param cc char input
 * @param bc byte output
 */
public void convert(CharChunk cc, ByteChunk bc) throws IOException {
    if ((bb == null) || (bb.array() != bc.getBuffer())) {
        // Create a new byte buffer if anything changed
        bb = ByteBuffer.wrap(bc.getBuffer(), bc.getEnd(), bc.getBuffer().length - bc.getEnd());
    } else {
        // Initialize the byte buffer
        bb.limit(bc.getBuffer().length);
        bb.position(bc.getEnd());
    }
    if ((cb == null) || (cb.array() != cc.getBuffer())) {
        // Create a new char buffer if anything changed
        cb = CharBuffer.wrap(cc.getBuffer(), cc.getStart(), cc.getLength());
    } else {
        // Initialize the char buffer
        cb.limit(cc.getEnd());
        cb.position(cc.getStart());
    }
    CoderResult result = null;
    // Parse leftover if any are present
    if (leftovers.position() > 0) {
        int pos = bb.position();
        // Loop until one char is encoded or there is a encoder error
        do {
            leftovers.put((char) cc.substract());
            leftovers.flip();
            result = encoder.encode(leftovers, bb, false);
            leftovers.position(leftovers.limit());
            leftovers.limit(leftovers.array().length);
        } while (result.isUnderflow() && (bb.position() == pos));
        if (result.isError() || result.isMalformed()) {
            result.throwException();
        }
        cb.position(cc.getStart());
        leftovers.position(0);
    }
    // Do the decoding and get the results into the byte chunk and the char
    // chunk
    result = encoder.encode(cb, bb, false);
    if (result.isError() || result.isMalformed()) {
        result.throwException();
    } else if (result.isOverflow()) {
        // Propagate current positions to the byte chunk and char chunk
        bc.setEnd(bb.position());
        cc.setOffset(cb.position());
    } else if (result.isUnderflow()) {
        // Propagate current positions to the byte chunk and char chunk
        bc.setEnd(bb.position());
        cc.setOffset(cb.position());
        // Put leftovers in the leftovers char buffer
        if (cc.getLength() > 0) {
            leftovers.limit(leftovers.array().length);
            leftovers.position(cc.getLength());
            cc.substract(leftovers.array(), 0, cc.getLength());
        }
    }
}
Also used : CoderResult(java.nio.charset.CoderResult)

Example 72 with CoderResult

use of java.nio.charset.CoderResult in project logging-log4j2 by apache.

the class TextEncoderHelper method flushRemainingBytes.

private static void flushRemainingBytes(final CharsetEncoder charsetEncoder, final ByteBufferDestination destination, ByteBuffer temp) {
    CoderResult result;
    do {
        // write any final bytes to the output buffer once the overall input sequence has been read
        result = charsetEncoder.flush(temp);
        temp = drainIfByteBufferFull(destination, temp, result);
    } while (// byte buffer has been drained: retry
    result.isOverflow());
    if (!result.isUnderflow()) {
        // we should have fully flushed the remaining bytes
        throwException(result);
    }
    if (temp.remaining() > 0 && temp != destination.getByteBuffer()) {
        temp.flip();
        ByteBufferDestinationHelper.writeToUnsynchronized(temp, destination);
        temp.clear();
    }
}
Also used : CoderResult(java.nio.charset.CoderResult)

Example 73 with CoderResult

use of java.nio.charset.CoderResult in project logging-log4j2 by apache.

the class TextEncoderHelper method encodeAsMuchAsPossible.

private static ByteBuffer encodeAsMuchAsPossible(final CharsetEncoder charsetEncoder, final CharBuffer charBuf, final boolean endOfInput, final ByteBufferDestination destination, ByteBuffer temp) {
    CoderResult result;
    do {
        result = charsetEncoder.encode(charBuf, temp, endOfInput);
        temp = drainIfByteBufferFull(destination, temp, result);
    } while (// byte buffer has been drained: retry
    result.isOverflow());
    if (!result.isUnderflow()) {
        // we should have fully read the char buffer contents
        throwException(result);
    }
    return temp;
}
Also used : CoderResult(java.nio.charset.CoderResult)

Example 74 with CoderResult

use of java.nio.charset.CoderResult in project cassandra by apache.

the class CBUtil method decodeString.

// Taken from Netty's ChannelBuffers.decodeString(). We need to use our own decoder to properly handle invalid
// UTF-8 sequences.  See CASSANDRA-8101 for more details.  This can be removed once https://github.com/netty/netty/pull/2999
// is resolved in a release used by Cassandra.
private static String decodeString(ByteBuffer src) throws CharacterCodingException {
    // the decoder needs to be reset every time we use it, hence the copy per thread
    CharsetDecoder theDecoder = TL_UTF8_DECODER.get();
    theDecoder.reset();
    CharBuffer dst = TL_CHAR_BUFFER.get();
    int capacity = (int) ((double) src.remaining() * theDecoder.maxCharsPerByte());
    if (dst == null) {
        capacity = Math.max(capacity, 4096);
        dst = CharBuffer.allocate(capacity);
        TL_CHAR_BUFFER.set(dst);
    } else {
        dst.clear();
        if (dst.capacity() < capacity) {
            dst = CharBuffer.allocate(capacity);
            TL_CHAR_BUFFER.set(dst);
        }
    }
    CoderResult cr = theDecoder.decode(src, dst, true);
    if (!cr.isUnderflow())
        cr.throwException();
    return dst.flip().toString();
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) CharBuffer(java.nio.CharBuffer) CoderResult(java.nio.charset.CoderResult)

Example 75 with CoderResult

use of java.nio.charset.CoderResult in project tomcat by apache.

the class WsFrameBase method processDataControl.

private boolean processDataControl() throws IOException {
    TransformationResult tr = transformation.getMoreData(opCode, fin, rsv, controlBufferBinary);
    if (TransformationResult.UNDERFLOW.equals(tr)) {
        return false;
    }
    // Control messages have fixed message size so
    // TransformationResult.OVERFLOW is not possible here
    controlBufferBinary.flip();
    if (opCode == Constants.OPCODE_CLOSE) {
        open = false;
        String reason = null;
        int code = CloseCodes.NORMAL_CLOSURE.getCode();
        if (controlBufferBinary.remaining() == 1) {
            controlBufferBinary.clear();
            // Payload must be zero or 2+ bytes long
            throw new WsIOException(new CloseReason(CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.oneByteCloseCode")));
        }
        if (controlBufferBinary.remaining() > 1) {
            code = controlBufferBinary.getShort();
            if (controlBufferBinary.remaining() > 0) {
                CoderResult cr = utf8DecoderControl.decode(controlBufferBinary, controlBufferText, true);
                if (cr.isError()) {
                    controlBufferBinary.clear();
                    controlBufferText.clear();
                    throw new WsIOException(new CloseReason(CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.invalidUtf8Close")));
                }
                // There will be no overflow as the output buffer is big
                // enough. There will be no underflow as all the data is
                // passed to the decoder in a single call.
                controlBufferText.flip();
                reason = controlBufferText.toString();
            }
        }
        wsSession.onClose(new CloseReason(Util.getCloseCode(code), reason));
    } else if (opCode == Constants.OPCODE_PING) {
        if (wsSession.isOpen()) {
            wsSession.getBasicRemote().sendPong(controlBufferBinary);
        }
    } else if (opCode == Constants.OPCODE_PONG) {
        MessageHandler.Whole<PongMessage> mhPong = wsSession.getPongMessageHandler();
        if (mhPong != null) {
            try {
                mhPong.onMessage(new WsPongMessage(controlBufferBinary));
            } catch (Throwable t) {
                handleThrowableOnSend(t);
            } finally {
                controlBufferBinary.clear();
            }
        }
    } else {
        // Should have caught this earlier but just in case...
        controlBufferBinary.clear();
        throw new WsIOException(new CloseReason(CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.invalidOpCode", Integer.valueOf(opCode))));
    }
    controlBufferBinary.clear();
    newFrame();
    return true;
}
Also used : MessageHandler(jakarta.websocket.MessageHandler) CloseReason(jakarta.websocket.CloseReason) PongMessage(jakarta.websocket.PongMessage) 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