@Override protected void produceData(final StreamChannel<ByteBuffer> channel) throws IOException { final int chunk = Math.min((int) (remaining < Integer.MAX_VALUE ? remaining : Integer.MAX_VALUE), buffer.remaining()); for (int i = 0; i < chunk; i++) { final byte b = RANGE[(int) (Math.random() * RANGE.length)]; buffer.put(b); } buffer.flip(); final int bytesWritten = channel.write(buffer); if (bytesWritten > 0) { remaining -= bytesWritten; } buffer.compact(); if (remaining <= 0) { channel.endStream(); } }
private void flush(final StreamChannel<ByteBuffer> channel) throws IOException { if (bytebuf.position() > 0) { bytebuf.flip(); channel.write(bytebuf); bytebuf.compact(); } }
final void streamEnd(final StreamChannel<ByteBuffer> channel) throws IOException { if (state == State.ACTIVE) { state = State.FLUSHING; flush(channel); if (bytebuf.position() == 0) { state = State.END_STREAM; channel.endStream(); } } }
private void flush(final StreamChannel<ByteBuffer> channel) throws IOException { if (bytebuf.position() > 0) { bytebuf.flip(); channel.write(bytebuf); bytebuf.compact(); } }
final void streamEnd(final StreamChannel<ByteBuffer> channel) throws IOException { if (state == State.ACTIVE) { state = State.FLUSHING; if (!bytebuf.hasRemaining()) { flush(channel); } final CoderResult result = charsetEncoder.encode(EMPTY, bytebuf, true); if (result.isError()) { result.throwException(); } final CoderResult result2 = charsetEncoder.flush(bytebuf); if (result2.isError()) { result.throwException(); } else if (result.isUnderflow()) { flush(channel); if (bytebuf.position() == 0) { state = State.END_STREAM; channel.endStream(); } } } }
final int writeData(final StreamChannel<ByteBuffer> channel, final ByteBuffer src) throws IOException { final int chunk = src.remaining(); if (chunk == 0) { return 0; } if (chunk > fragmentSizeHint) { // the data chunk is greater than the fragment hint // attempt to write it out to the channel directly // flush the buffer if not empty flush(channel); if (bytebuf.position() == 0) { return channel.write(src); } } else { // the data chunk is smaller than the fragment hint // attempt to buffer it // flush the buffer if there is not enough space to store the chunk if (bytebuf.remaining() < chunk) { flush(channel); } if (bytebuf.remaining() >= chunk) { bytebuf.put(src); if (!bytebuf.hasRemaining()) { flush(channel); } return chunk; } } return 0; }