Java Code Examples for java.nio.BufferOverflowException

The following examples show how to use java.nio.BufferOverflowException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Tomcat8-Source-Read   Source File: BufferedInputFilter.java    License: MIT License 6 votes vote down vote up
/**
 * 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");
    }
}
 
Example 2
Source Project: Bytecoder   Source File: PostHandshakeContext.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 3
Source Project: lucene-solr   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
  };

}
 
Example 4
Source Project: catalyst   Source File: AbstractBuffer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
@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;
}
 
Example 6
/**
 * 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;
}
 
Example 7
@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);
    }
}
 
Example 8
/**
 *  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 !");
	}
}
 
Example 9
Source Project: hbase   Source File: MultiByteBuff.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 10
@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);
}
 
Example 11
Source Project: 365browser   Source File: CodedOutputByteBufferNano.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example 12
Source Project: directory-ldap-api   Source File: AndFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 13
Source Project: atomix   Source File: SegmentedJournalWriter.java    License: Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example 14
Source Project: kieker   Source File: BinaryLogStreamHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example 15
Source Project: directory-ldap-api   Source File: BerValue.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
    }
}
 
Example 16
Source Project: j2objc   Source File: Edits.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 17
Source Project: directory-ldap-api   Source File: BerValue.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
    }
}
 
Example 18
Source Project: directory-ldap-api   Source File: BerValue.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
    }
}
 
Example 19
Source Project: kieker   Source File: ActivationParameterEvent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@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]);
}
 
Example 20
Source Project: t-io   Source File: Buffers.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 21
Source Project: jmonkeyengine   Source File: IosGL.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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);
}
 
Example 22
Source Project: kieker   Source File: BeforeOperationObjectEvent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@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());
}
 
Example 23
Source Project: kieker   Source File: BeforeReceivedRemoteEvent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@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());
}
 
Example 24
Source Project: kieker   Source File: ConstructionEvent.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@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());
}
 
Example 25
Source Project: openjsse   Source File: HandshakeContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
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();
}
 
Example 26
/**
 * {@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;
}
 
Example 27
Source Project: p4ic4idea   Source File: RpcPacketField.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 28
Source Project: Rumble   Source File: BlockHeader.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
    }
}
 
Example 29
Source Project: hadoop-gpu   Source File: DFSClient.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 30
Source Project: qpid-broker-j   Source File: MultiQpidByteBuffer.java    License: Apache License 2.0 5 votes vote down vote up
@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());
    }
}