EndOfLineBuffer { public boolean write(final byte data){ if (isEndOfLine()){ throw new IllegalStateException("Buffer is in an end of line state. You need to recycle it before writing."); } flushIfNeeded(); circularBuffer.write(data); boolean isEndOfLine = updateEndOfLineMatchingStatus(data); if (isEndOfLine){ flushIfNeeded(); } return isEndOfLine; } EndOfLineBuffer(final int size, byte[] endOfLineSequence, final OutputStream flushOutputStream); void recycle(final byte[] endOfLineSequence, final OutputStream flushOutputStream); boolean write(final byte data); boolean isEndOfLine();  }
@Test public void testWrite() throws Exception { ByteArrayOutputStream flush = new ByteArrayOutputStream(); EndOfLineBuffer endOfLineBuffer = new EndOfLineBuffer(10, new byte[]{0x0D, 0x0A}, flush); log.info("Buffer initial status:\n" + endOfLineBufferToString(endOfLineBuffer) + "\n"); int writtenBytes = writeDataToEndOfLineBuffer(endOfLineBuffer, new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x0D, 0x0A, 0x08, 0x09, 0x10}); assertEquals(9, writtenBytes); assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}, flush.toByteArray()); flush.reset(); endOfLineBuffer.recycle(new byte[]{0x0D, 0x0A}, flush); writtenBytes = writeDataToEndOfLineBuffer(endOfLineBuffer, new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x0D, 0x0D, 0x0A, 0x09, 0x10}); assertEquals(10, writtenBytes); assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x0D}, flush.toByteArray()); }
@Test public void testWrite_flush_error() throws Exception { OutputStream flush = mock(OutputStream.class); byte failingWrite = 10; doThrow(new IOException("mock throwing the exception")).when(flush).write(any(byte[].class), anyInt(), anyInt()); EndOfLineBuffer endOfLineBuffer = new EndOfLineBuffer(10, new byte[]{0x0D, 0x0A}, flush); log.info("Buffer initial status:\n" + endOfLineBufferToString(endOfLineBuffer) + "\n"); writeDataToEndOfLineBuffer(endOfLineBuffer, new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, failingWrite}); Exception expected = null; try{ endOfLineBuffer.write((byte)1); }catch (Exception e){ expected = e; } assertNotNull(expected); assertTrue(expected instanceof IllegalStateException); }