java.nio.BufferOverflowException Java Examples

The following examples show how to use java.nio.BufferOverflowException. 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 File: AbstractBuffer.java    From catalyst with 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 #2
Source File: SegmentedJournalWriter.java    From atomix with 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 #3
Source File: AbstractJsonifiableWithDittoHeadersSerializer.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@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 #4
Source File: FileRecordBuffer.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 *  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 #5
Source File: BinaryFormatSerializer.java    From realtime-analytics with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: IntentDownloadService.java    From YTPlayer with GNU General Public License v3.0 6 votes vote down vote up
@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 #7
Source File: BinaryLogStreamHandlerTest.java    From kieker with 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 #8
Source File: MultiByteBuff.java    From hbase with 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 #9
Source File: AndFilter.java    From directory-ldap-api with 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 #10
Source File: AbstractKaitaiGenerator.java    From JQF with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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 File: BerValue.java    From directory-ldap-api with 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 #12
Source File: CodedOutputByteBufferNano.java    From 365browser with 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 #13
Source File: Utils.java    From lucene-solr with 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 #14
Source File: Edits.java    From j2objc with 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 #15
Source File: PostHandshakeContext.java    From Bytecoder with 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 #16
Source File: BerValue.java    From directory-ldap-api with 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 #17
Source File: BerValue.java    From directory-ldap-api with 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 #18
Source File: BufferedInputFilter.java    From Tomcat8-Source-Read with 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 #19
Source File: AfterConstructorFailedObjectEvent.java    From kieker with 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.putString(this.getCause());
	serializer.putInt(this.getObjectId());
}
 
Example #20
Source File: Serializer.java    From AVM with MIT License 5 votes vote down vote up
private static void serializeClassStatics(ByteBufferObjectSerializer objectSerializer, SortedFieldCache cache, Class<?>[] sortedRoots, Class<?> constantClass) {
    try {
        // First, we serialize the constants.
        serializeConstantClass(objectSerializer, cache, constantClass);
        // Then, we serialize the user-defined static fields.
        for (Class<?> clazz : sortedRoots) {
            serializeOneUserClass(objectSerializer, cache, clazz);
        }
    } catch (BufferOverflowException e) {
        // This is if we run off the end of the buffer, which is an example of out of energy.
        throw new OutOfEnergyException();
    }
}
 
Example #21
Source File: AfterOperationFailedObjectEvent.java    From kieker with 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.putString(this.getCause());
	serializer.putInt(this.getObjectId());
}
 
Example #22
Source File: NamedDoubleRecord.java    From kieker with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void serialize(final IValueSerializer serializer) throws BufferOverflowException {
	serializer.putString(this.getApplicationName());
	serializer.putLong(this.getTimestamp());
	serializer.putDouble(this.getResponseTime());
}
 
Example #23
Source File: BBEncoder.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
   public void writeInt32(int anInt)
{
	try
	{
		out.putInt(anInt);
	} catch(BufferOverflowException exception)
	{
		grow(4);
		out.putInt(anInt);
	}
}
 
Example #24
Source File: HttpClientPool.java    From message_interface with MIT License 5 votes vote down vote up
private static ByteBuffer ensureCapacity(ByteBuffer buffer, int requirement, int increment) throws BufferOverflowException {
    if (buffer.remaining() >= requirement) {
        return buffer;
    }

    int newCapacity = buffer.capacity() + increment;

    ByteBuffer newBuffer = ByteBuffer.allocate(newCapacity);
    newBuffer.put(buffer);
    return newBuffer;
}
 
Example #25
Source File: GelfBuffers.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * Create UDP buffers and apply auto-buffer-enlarging, if necessary.
 *
 * @param message
 * @param writeBuffers
 * @param tempBuffers
 * @return
 */
protected static ByteBuffer[] toUDPBuffers(GelfMessage message, ThreadLocal<ByteBuffer> writeBuffers,
        ThreadLocal<ByteBuffer> tempBuffers) {

    while (true) {

        try {
            return message.toUDPBuffers(getBuffer(writeBuffers), getBuffer(tempBuffers));
        } catch (BufferOverflowException e) {
            enlargeBuffer(writeBuffers);
            enlargeBuffer(tempBuffers);
        }
    }
}
 
Example #26
Source File: BitmapSerializerTest.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Test
public void testBitmapSerDe() {
    BitmapSerializer serializer = new BitmapSerializer(DataType.ANY);

    BitmapCounter counter = RoaringBitmapCounterFactory.INSTANCE.newBitmap(1, 1234, 5678, 100000);

    ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
    serializer.serialize(counter, buffer);
    int size = buffer.position();
    buffer.flip();

    assertEquals(size, serializer.peekLength(buffer));
    assertEquals(0, buffer.position()); // peek doesn't change buffer

    BitmapCounter counter2 = serializer.deserialize(buffer);
    assertEquals(size, buffer.position()); // deserialize advance positions to next record
    assertEquals(4, counter2.getCount());

    buffer.flip();
    for (int i = 0; i < size; i++) {
        buffer.put((byte) 0); // clear buffer content
    }
    assertEquals(4, counter2.getCount());

    buffer = ByteBuffer.allocate(size - 1);
    try {
        serializer.serialize(counter, buffer);
        Assert.fail();
    } catch (Exception e) {
        assertTrue(e instanceof BufferOverflowException);
    }
}
 
Example #27
Source File: JoinEvent.java    From kieker with 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.putLong(this.getJoinedTraceId());
}
 
Example #28
Source File: Lz4BlockCompressor.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public int compress(ByteBuffer src, int srcOff, int srcLen, ByteBuffer dst, int dstOff)
		throws InsufficientBufferException {
	try {
		final int prevSrcOff = src.position() + srcOff;
		final int prevDstOff = dst.position() + dstOff;

		int maxCompressedSize = compressor.maxCompressedLength(srcLen);
		int compressedLength = compressor.compress(
				src,
				prevSrcOff,
				srcLen,
				dst,
				prevDstOff + HEADER_LENGTH,
				maxCompressedSize
		);

		src.position(prevSrcOff + srcLen);

		dst.position(prevDstOff);
		dst.order(ByteOrder.LITTLE_ENDIAN);
		dst.putInt(compressedLength);
		dst.putInt(srcLen);
		dst.position(prevDstOff + compressedLength + HEADER_LENGTH);

		return HEADER_LENGTH + compressedLength;
	}
	catch (LZ4Exception | ArrayIndexOutOfBoundsException | BufferOverflowException e) {
		throw new InsufficientBufferException(e);
	}
}
 
Example #29
Source File: CompressingDataRecordSerializer.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void serialize(CloverBuffer buffer, ListDataField field) {
	try {
		// encode null as zero, increment size of non-null values by one
		ByteBufferUtils.encodeLength(buffer, field.isNull ? 0 : field.getSize() + 1);

		for (DataField lfield : field) {
			lfield.serialize(buffer,this);
		}
   	} catch (BufferOverflowException e) {
   		throw new RuntimeException("The size of data buffer is only " + buffer.maximumCapacity() + ". Set appropriate parameter in defaultProperties file.", e);
   	}

}
 
Example #30
Source File: ActivationParameterEvent.java    From kieker with 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]);
}