下面列出了怎么用java.nio.BufferOverflowException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Reads the request body and buffers it.
*/
@Override
public void setRequest(Request request) {
// save off the Request body
try {
while (buffer.doRead(this) >= 0) {
buffered.mark().position(buffered.limit()).limit(buffered.capacity());
buffered.put(tempRead);
buffered.limit(buffered.position()).reset();
tempRead = null;
}
} catch(IOException | BufferOverflowException ioe) {
// No need for i18n - this isn't going to get logged anywhere
throw new IllegalStateException(
"Request body too large for buffer");
}
}
@Override
void dispatch(byte handshakeType, ByteBuffer fragment) throws IOException {
SSLConsumer consumer = handshakeConsumers.get(handshakeType);
if (consumer == null) {
throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,
"Unexpected post-handshake message: " +
SSLHandshake.nameOf(handshakeType));
}
try {
consumer.consume(this, fragment);
} catch (UnsupportedOperationException unsoe) {
throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,
"Unsupported post-handshake message: " +
SSLHandshake.nameOf(handshakeType), unsoe);
} catch (BufferUnderflowException | BufferOverflowException be) {
throw conContext.fatal(Alert.DECODE_ERROR,
"Illegal handshake message: " +
SSLHandshake.nameOf(handshakeType), be);
}
}
public static InputStreamConsumer<ByteBuffer> newBytesConsumer(int maxSize) {
return is -> {
try (BinaryRequestWriter.BAOS bos = new BinaryRequestWriter.BAOS()) {
long sz = 0;
int next = is.read();
while (next > -1) {
if (++sz > maxSize) throw new BufferOverflowException();
bos.write(next);
next = is.read();
}
bos.flush();
return ByteBuffer.wrap(bos.getbuf(), 0, bos.size());
} catch (IOException e) {
throw new RuntimeException(e);
}
};
}
/**
* Checks bounds for a write.
*/
protected long checkWrite(long offset, long length) {
checkOffset(offset);
if (limit == -1) {
if (offset + length > capacity) {
if (capacity < maxCapacity) {
capacity(calculateCapacity(offset + length));
} else {
throw new BufferOverflowException();
}
}
} else {
if (offset + length > limit)
throw new BufferOverflowException();
}
return offset(offset);
}
@Override
public int write(ByteBuffer inputBuffer) {
int inputBytes = inputBuffer.remaining();
if (inputBytes > byteBuffer.remaining()) {
dumpToFile();
byteBuffer.clear();
if (inputBytes > byteBuffer.remaining()) {
throw new BufferOverflowException();
}
}
byteBuffer.put(inputBuffer);
return inputBytes;
}
/**
* Serialize the session metadata to a bytebuffer.
*
* The bytebuffer will be reused, the caller should copy out the contents
* when pass the content.
*
* @param session
* @return
*/
public ByteBuffer getSessionMetadata(Session session) {
ByteBuffer buffer = ByteBufferUtil.getThreadLocalByteBuffer();
while (true) {
try {
buffer.clear();
buffer.put(SESSION_VERSION);
bytePrimitiveEncoder.encode(session.getInitialAttributes(), buffer);
buffer.flip();
break;
} catch (BufferOverflowException ex) {
buffer = ByteBufferUtil.enlargeThreadLocalByteBuffer();
}
}
ByteBuffer bufferCopy = ByteBuffer.allocate(buffer.limit());
bufferCopy.put(buffer);
bufferCopy.clear();
return bufferCopy;
}
@Override
public byte[] toBinary(final Object object) {
final ByteBuffer buf = byteBufferPool.acquire();
try {
toBinary(object, buf);
buf.flip();
final byte[] bytes = new byte[buf.remaining()];
buf.get(bytes);
return bytes;
} catch (final BufferOverflowException e) {
final String errorMessage =
MessageFormat.format("BufferOverflow when serializing object <{0}>, max buffer size was: <{1}>",
object, defaultBufferSize);
LOG.error(errorMessage, e);
throw new IllegalArgumentException(errorMessage, e);
} finally {
byteBufferPool.release(buf);
}
}
/**
* Stores one data record into buffer.
*
*@param data ByteBuffer containing record's data
*@exception IOException In case of IO failure
*@since September 17, 2002
*/
public void push(CloverBuffer data) throws IOException {
if(isClosed){
throw new IOException("Buffer has been closed !");
}
int recordSize = data.remaining();
secureBuffer(writePosition, recordSize + LEN_SIZE_SPECIFIER);
try {
dataBuffer.position((int)(writePosition - mapPosition));
dataBuffer.putInt(recordSize);
dataBuffer.put(data);
writePosition += (recordSize + LEN_SIZE_SPECIFIER);
isDirty = true;
} catch (BufferOverflowException ex) {
throw new IOException("Input Buffer is not big enough to accomodate data record !");
}
}
/**
* Writes an int to this MBB at its current position. Also advances the position by size of int
* @param val Int value to write
* @return this object
*/
@Override
public MultiByteBuff putInt(int val) {
checkRefCount();
if (this.curItem.remaining() >= Bytes.SIZEOF_INT) {
this.curItem.putInt(val);
return this;
}
if (this.curItemIndex == this.items.length - 1) {
throw new BufferOverflowException();
}
// During read, we will read as byte by byte for this case. So just write in Big endian
put(int3(val));
put(int2(val));
put(int1(val));
put(int0(val));
return this;
}
@Override
public InputStream generate(SourceOfRandomness random, GenerationStatus status) {
buf = ByteBuffer.allocate(this.capacity);
try {
// Populate byte buffer
populate(random);
} catch (BufferOverflowException e) {
// throw new AssumptionViolatedException("Generated input is too large", e);
}
// Return the bytes as an inputstream
int len = buf.position();
buf.rewind();
byte[] bytes = new byte[len];
buf.get(bytes);
return new ByteArrayInputStream(bytes);
}
/**
* Encodes {@code sequence} into UTF-8, in {@code byteBuffer}. For a string, this method is
* equivalent to {@code buffer.put(string.getBytes(UTF_8))}, but is more efficient in both time
* and space. Bytes are written starting at the current position. This method requires paired
* surrogates, and therefore does not support chunking.
*
* <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to
* compute the exact amount needed, or leave room for {@code 3 * sequence.length()}, which is the
* largest possible number of bytes that any input can be encoded to.
*
* @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired
* surrogates)
* @throws BufferOverflowException if {@code sequence} encoded in UTF-8 does not fit in
* {@code byteBuffer}'s remaining space.
* @throws ReadOnlyBufferException if {@code byteBuffer} is a read-only buffer.
*/
private static void encode(CharSequence sequence, ByteBuffer byteBuffer) {
if (byteBuffer.isReadOnly()) {
throw new ReadOnlyBufferException();
} else if (byteBuffer.hasArray()) {
try {
int encoded = encode(sequence,
byteBuffer.array(),
byteBuffer.arrayOffset() + byteBuffer.position(),
byteBuffer.remaining());
byteBuffer.position(encoded - byteBuffer.arrayOffset());
} catch (ArrayIndexOutOfBoundsException e) {
BufferOverflowException boe = new BufferOverflowException();
boe.initCause(e);
throw boe;
}
} else {
encodeDirect(sequence, byteBuffer);
}
}
/**
* Encode the AndFilter message to a PDU.
* <br>
* AndFilter :
* <pre>
* 0xA0 LL
* filter.encode() ... filter.encode()
* </pre>
*
* @param buffer The buffer where to put the PDU
* @return The PDU.
*/
@Override
public ByteBuffer encode( ByteBuffer buffer ) throws EncoderException
{
if ( buffer == null )
{
throw new EncoderException( I18n.err( I18n.ERR_08000_CANNOT_PUT_A_PDU_IN_NULL_BUFFER ) );
}
try
{
// The AndFilter Tag
buffer.put( ( byte ) LdapCodecConstants.AND_FILTER_TAG );
buffer.put( TLV.getBytes( filtersLength ) );
}
catch ( BufferOverflowException boe )
{
throw new EncoderException( I18n.err( I18n.ERR_08212_PDU_BUFFER_TOO_SMALL ), boe );
}
super.encode( buffer );
return buffer;
}
@Override
public void append(Indexed<E> entry) {
try {
currentWriter.append(entry);
} catch (BufferOverflowException e) {
if (currentSegment.index() == currentWriter.getNextIndex()) {
throw e;
}
currentWriter.flush();
currentSegment.release();
currentSegment = journal.getNextSegment();
currentSegment.acquire();
currentWriter = currentSegment.writer();
currentWriter.append(entry);
}
}
@Test
public void testSerializeBufferTooTiny() throws IOException {
final IMonitoringRecord record = new OperationExecutionRecord("testing", "abc", 1, 0, 1, "localhost", 123, 456);
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final BinaryLogStreamHandler handler = new BinaryLogStreamHandler(true, 10,
this.charset, this.compressionFilter, this.reg);
try {
// channel initializing
handler.initialize(byteArrayOutputStream, Paths.get("test-filename"));
// serializing test record
handler.serialize(record, 2);
Assert.fail("Code should trigger an exception and not reach this point.");
} catch (final BufferOverflowException e) { // NOPMD
// as buffer size is to small it will always catch exception
} finally {
byteArrayOutputStream.close();
}
}
/**
* Encode a BIT STRING value
*
* @param buffer The PDU in which the value will be put
* @param bitString The BitString to be encoded.
* @throws EncoderException if the PDU in which the value should be encoded is
* two small
*/
public static void encode( ByteBuffer buffer, BitString bitString ) throws EncoderException
{
if ( buffer == null )
{
throw new EncoderException( I18n.err( I18n.ERR_01300_CANNOT_PUT_PDU_IN_NULL_BUFFER ) );
}
try
{
buffer.put( UniversalTag.BIT_STRING.getValue() );
// The BitString length. We add one byte for the unused number
// of bits
byte[] bytes = bitString.getData();
int length = bytes.length;
buffer.put( TLV.getBytes( length ) );
buffer.put( bytes );
}
catch ( BufferOverflowException boe )
{
throw new EncoderException( I18n.err( I18n.ERR_01301_PDU_BUFFER_SIZE_TOO_SMALL ), boe );
}
}
private boolean growArray() {
int newCapacity;
if (array.length == STACK_CAPACITY) {
newCapacity = 2000;
} else if (array.length == Integer.MAX_VALUE) {
throw new BufferOverflowException();
} else if (array.length >= (Integer.MAX_VALUE / 2)) {
newCapacity = Integer.MAX_VALUE;
} else {
newCapacity = 2 * array.length;
}
// Grow by at least 5 units so that a maximal change record will fit.
if ((newCapacity - array.length) < 5) {
throw new BufferOverflowException();
}
array = Arrays.copyOf(array, newCapacity);
return true;
}
/**
* Encode an enumerated value
*
* @param buffer The PDU in which the value will be put
* @param value The integer to be encoded
* @throws EncoderException if the PDU in which the value should be encoded is
* two small
*/
public static void encodeEnumerated( ByteBuffer buffer, int value ) throws EncoderException
{
if ( buffer == null )
{
throw new EncoderException( I18n.err( I18n.ERR_01300_CANNOT_PUT_PDU_IN_NULL_BUFFER ) );
}
try
{
buffer.put( UniversalTag.ENUMERATED.getValue() );
buffer.put( TLV.getBytes( getNbBytes( value ) ) );
buffer.put( getBytes( value ) );
}
catch ( BufferOverflowException boe )
{
throw new EncoderException( I18n.err( I18n.ERR_01301_PDU_BUFFER_SIZE_TOO_SMALL ), boe );
}
}
/**
* Encode a boolean value
*
* @param buffer The PDU in which the value will be put
* @param bool The boolean to be encoded
* @throws EncoderException if the PDU in which the value should be encoded is
* two small
*/
public static void encode( ByteBuffer buffer, boolean bool ) throws EncoderException
{
if ( buffer == null )
{
throw new EncoderException( I18n.err( I18n.ERR_01300_CANNOT_PUT_PDU_IN_NULL_BUFFER ) );
}
try
{
if ( bool )
{
buffer.put( ENCODED_TRUE );
}
else
{
buffer.put( ENCODED_FALSE );
}
}
catch ( BufferOverflowException boe )
{
throw new EncoderException( I18n.err( I18n.ERR_01301_PDU_BUFFER_SIZE_TOO_SMALL ), boe );
}
}
/**
* {@inheritDoc}
*/
@Override
public void serialize(final IValueSerializer serializer) throws BufferOverflowException {
serializer.putString(this.getPattern());
serializer.putString(this.getName());
// store array sizes
int _values_size0 = this.getValues().length;
serializer.putInt(_values_size0);
for (int i0=0;i0<_values_size0;i0++)
serializer.putString(this.getValues()[i0]);
}
ByteBuffer grow(BufferType b, int recommendedBufferSize) {
ByteBuffer originalBuffer = get(b);
ByteBuffer newBuffer = ByteBuffer.allocate(recommendedBufferSize);
try {
//debug("grow buffer " + originalBuffer + " to " + newBuffer);
BufferUtils.copy(originalBuffer, newBuffer);
} catch (BufferOverflowException e) {
throw e;
}
return newBuffer;
}
private void fromArray(int n, int[] array, IntBuffer buffer) {
if (buffer.remaining() < n) {
throw new BufferOverflowException();
}
int pos = buffer.position();
buffer.put(array, 0, n);
buffer.position(pos);
}
/**
* {@inheritDoc}
*/
@Override
public void serialize(final IValueSerializer serializer) throws BufferOverflowException {
serializer.putLong(this.getTimestamp());
serializer.putLong(this.getTraceId());
serializer.putInt(this.getOrderIndex());
serializer.putString(this.getOperationSignature());
serializer.putString(this.getClassSignature());
serializer.putInt(this.getObjectId());
}
/**
* {@inheritDoc}
*/
@Override
public void serialize(final IValueSerializer serializer) throws BufferOverflowException {
serializer.putLong(this.getTimestamp());
serializer.putLong(this.getCallerTraceId());
serializer.putInt(this.getCallerOrderIndex());
serializer.putLong(this.getTraceId());
serializer.putInt(this.getOrderIndex());
}
/**
* {@inheritDoc}
*/
@Override
public void serialize(final IValueSerializer serializer) throws BufferOverflowException {
serializer.putLong(this.getTimestamp());
serializer.putLong(this.getTraceId());
serializer.putInt(this.getOrderIndex());
serializer.putString(this.getClassSignature());
serializer.putInt(this.getObjectId());
}
void dispatch(byte handshakeType,
ByteBuffer fragment) throws IOException {
SSLConsumer consumer;
if (handshakeType == SSLHandshake.HELLO_REQUEST.id) {
// For TLS 1.2 and prior versions, the HelloRequest message MAY
// be sent by the server at any time.
consumer = SSLHandshake.HELLO_REQUEST;
} else {
consumer = handshakeConsumers.get(handshakeType);
}
if (consumer == null) {
throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,
"Unexpected handshake message: " +
SSLHandshake.nameOf(handshakeType));
}
try {
consumer.consume(this, fragment);
} catch (UnsupportedOperationException unsoe) {
throw conContext.fatal(Alert.UNEXPECTED_MESSAGE,
"Unsupported handshake message: " +
SSLHandshake.nameOf(handshakeType), unsoe);
} catch (BufferUnderflowException | BufferOverflowException be) {
throw conContext.fatal(Alert.DECODE_ERROR,
"Illegal handshake message: " +
SSLHandshake.nameOf(handshakeType), be);
}
// update handshake hash after handshake message consumption.
handshakeHash.consume();
}
/**
* {@inheritDoc}
*/
@Override
public final CloverBuffer putChar(char value) {
try {
buf.putChar(value);
} catch (BufferOverflowException e) {
if (autoExpand(2)) {
buf.putChar(value);
} else {
throw e;
}
}
return this;
}
/**
* Marshal the passed-in packet fields onto a ByteBuffer. Affects
* the buffer's position, etc., accordingly. Since this one uses
* special ByteBuffer to ByteBuffer methods, it gets its own
* version rather than using the byte[] method.<p>
*
* Note: incoming value ByteBuffer must have been flipped ready for
* sending; value's position will be updated by this method, so
* if the buffer is to be reused, you must flip or reset (or whatever)
* it yourself.<p>
*/
public static void marshal(ByteBuffer buf, String name, ByteBuffer value)
throws BufferOverflowException {
if (buf == null) {
throw new NullPointerError(
"Null byte buffer passed to RpcPacketField.marshal()");
}
try {
if (name != null) {
buf.put(name.getBytes(CharsetDefs.DEFAULT.name()));
}
buf.put((byte) 0);
int valLength = 0;
if (value != null) {
valLength = value.limit();
}
buf.put(RpcPacket.encodeInt4(valLength));
if (value != null) {
buf.put(value);
}
buf.put((byte) 0);
} catch (Throwable thr) {
Log.error("Unexpected exception: " + thr.getLocalizedMessage());
Log.exception(thr);
throw new P4JavaError("Unexpected exception in RpcPacketField.marshal(ByteBuffer): "
+ thr.getLocalizedMessage(), thr);
}
}
public long writeBlockHeader(OutputStream out) throws IOException {
ByteBuffer bufferBlockHeader = ByteBuffer.allocate(BLOCK_HEADER_LENGTH);
try {
bufferBlockHeader.put((byte)(version & 0xff));
bufferBlockHeader.put((byte)(transaction_type & 0xff));
bufferBlockHeader.put((byte) (
(reserved0 ? 1 : 0) << 7 |
(reserved1 ? 1 : 0) << 6 |
(reserved2 ? 1 : 0) << 5 |
(reserved3 ? 1 : 0) << 4 |
(reserved4 ? 1 : 0) << 3 |
(reserved5 ? 1 : 0) << 2 |
(reserved6 ? 1 : 0) << 1 |
(last_block ? 1 : 0)));
bufferBlockHeader.put((byte)(block_type & 0xff));
bufferBlockHeader.putLong(payload_length);
out.write(bufferBlockHeader.array());
bufferBlockHeader.clear();
BlockDebug.d(TAG, "BlockHeader sent (" + bufferBlockHeader.array().length + " bytes): " +Arrays.toString(bufferBlockHeader.array()));
return BLOCK_HEADER_LENGTH;
}
catch(BufferOverflowException e) {
BlockDebug.e(TAG, "[!] header overflow the buffer");
bufferBlockHeader.clear();
return 0;
}
}
void writeData(byte[] inarray, int off, int len) {
if ( dataPos + len > buf.length) {
throw new BufferOverflowException();
}
System.arraycopy(inarray, off, buf, dataPos, len);
dataPos += len;
}
@Override
public final void copyTo(final ByteBuffer dst)
{
if (dst.remaining() < remaining())
{
throw new BufferOverflowException();
}
for (int i = 0, fragmentsSize = _fragments.length; i < fragmentsSize; i++)
{
final SingleQpidByteBuffer fragment = _fragments[i];
dst.put(fragment.getUnderlyingBuffer().duplicate());
}
}