StreamPartReader { public static String readPart(Reader reader, char openingChar, char closingChar) throws IOException { StringBuilder part = new StringBuilder(PART_BUFFER_SIZE); int characterCode = reader.read(); int pairCounter = 0; char character; boolean read = false; while (characterCode != -1) { character = (char) characterCode; if (character == openingChar) { read = true; pairCounter++; } if (read) { part.append(character); } if (character == closingChar) { pairCounter--; if (pairCounter == 0) { break; } } characterCode = reader.read(); } if (pairCounter != 0) { throw new IllegalStateException("Stream ended but no ending char found! Possibly because of dangling opening char."); } return part.toString(); } private  StreamPartReader(); static String readPart(Reader reader, char openingChar, char closingChar);  }
@Test public void shouldReadPartFromBeginningCharacterToEndCharacterSkippingUnnecessaryPrefix() throws IOException { String text = "hello world!{ this is important }"; StringReader reader = new StringReader(text); String textPart = StreamPartReader.readPart(reader, '{', '}'); assertThat(textPart).isEqualTo("{ this is important }"); }
@Test public void shouldReadPartToEndCharacterLeavingSufixUnchangedInStream() throws IOException { String text = "{ this is important } leave me alone please"; StringReader reader = new StringReader(text); String textPart = StreamPartReader.readPart(reader, '{', '}'); assertThat(textPart).isEqualTo("{ this is important }"); assertThat(reader).hasTextLeft(" leave me alone please"); }
@Test public void shouldLookForOutermostCloseCharToPairWithOpenChar() throws IOException { String text = "{ { nested } this is important }"; StringReader reader = new StringReader(text); String textPart = StreamPartReader.readPart(reader, '{', '}'); assertThat(textPart).isEqualTo("{ { nested } this is important }"); }
@Test public void shouldThrowExceptionWhenDanglingOpeningCharacterDetected() throws IOException { String text = "{ this has danglign opening character"; StringReader reader = new StringReader(text); try { StreamPartReader.readPart(reader, '{', '}'); fail("expected IllegalState exception but none thrown"); } catch (IllegalStateException exception) { assertThat(exception).isInstanceOf(IllegalStateException.class); } }