### Question:
MatchlineScanner extends MultiLineScanner { @Override public TScanner wrap(InputStream in) { return new MatchlineScanner(codec, new InputStreamReader(in), head, tail); } MatchlineScanner();  MatchlineScanner(TDecoder codec,  Reader in, Pattern head, Pattern tail); @Override TScanner wrap(InputStream in);  }### Answer:
@Test public void testOnlyHead() throws Exception { String[] lines = new String[]{ "[2018-08-23] first", "[2018-08-23] second message1\nsecond message2", "[2018-08-23] last" }; String text = String.join("\n", lines); MatchlineScanner scanner = new MatchlineScanner(); scanner.head = Pattern.compile("^\\[\\d+-\\d+-\\d+] .*"); TScanner s = scanner.wrap(new ByteArrayInputStream(text.getBytes())); final AtomicInteger index = new AtomicInteger(); s.scan((event) -> { Assert.assertEquals(lines[index.getAndIncrement()], event.getSource()); return true; }); s.close(); }
@Test public void testHeadAndTail() throws Exception { JSONObject jack = new JSONObject(); jack.put("name", "Jack"); jack.put("age", 28); JSONObject mary = new JSONObject(); mary.put("name", "mary"); mary.put("age", 27); String[] blocks = new String[]{ JSON.toJSONString(jack, true), JSON.toJSONString(mary, true) }; String text = String.join("\n", blocks); MatchlineScanner scanner = new MatchlineScanner(); scanner.head = Pattern.compile("\\{$"); scanner.tail = Pattern.compile("\\}$"); TScanner s = scanner.wrap(new ByteArrayInputStream(text.getBytes())); final AtomicInteger index = new AtomicInteger(0); s.scan((event) -> { int idx = index.getAndIncrement(); Assert.assertEquals(blocks[idx], event.getSource()); return true; }); s.close(); }
@Test public void testOnlyTail() throws Exception { String[] blocks = new String[]{ "first block line1 \n first block line2 \n--", "second block line1\nsecond block line2\n second block line3\n--" }; String text = String.join("\n", blocks); MatchlineScanner scanner = new MatchlineScanner(); scanner.tail = Pattern.compile("--"); TScanner s = scanner.wrap(new ByteArrayInputStream(text.getBytes())); final AtomicInteger index = new AtomicInteger(); s.scan((event) -> { Assert.assertEquals(blocks[index.getAndIncrement()], event.getSource()); return true; }); s.close(); }