XMLTreeUtil { public static byte[] replaceAll(byte[] src, byte[] target, byte[] replacement) { final ByteArrayOutputStream result = new ByteArrayOutputStream(src.length); int i = 0; int wrote = 0; while ((i = indexOf(src, target, i)) != -1) { int len = i - wrote; result.write(src, wrote, len); result.write(replacement, 0, replacement.length); wrote += len + target.length; i += target.length; } result.write(src, wrote, src.length - wrote); return result.toByteArray(); } private  XMLTreeUtil(); static byte[] insertBetween(byte[] src, int left, int right, String content); static byte[] insertInto(byte[] src, int pos, String content); static T single(List<T> target); static int lastIndexOf(byte[] src, char c, int fromIdx); static int level(Element element); static int openTagLength(NewElement element); static int closeTagLength(NewElement element); static int attributeLength(NewAttribute attribute); static String tabulate(String src, int tabsCount); static Element asElement(Node node); static List<Element> asElements(NodeList list); static List<R> asElements(NodeList list, ElementMapper<? extends R> mapper); static int indexOf(byte[] src, byte[] target, int fromIdx); static int indexOfAttributeName(byte[] src, byte[] target, int fromIdx); static byte[] replaceAll(byte[] src, byte[] target, byte[] replacement); static int rootStart(byte[] xml); static final Charset UTF_8; static final int SPACES_IN_TAB; }
@Test public void shouldBeAbleToReplaceMoreBytesWithLessBytes() { final byte[] src = "\r\n\r\n text \r\n\r\n".getBytes(); final byte[] newSrc = replaceAll(src, "\r\n".getBytes(), "\n".getBytes()); assertEquals(newSrc, "\n\n text \n\n".getBytes()); }
@Test public void shouldBeAbleToReplaceLessBytesWithMoreBytes() { final byte[] src = "\n\n text \n\n text".getBytes(); final byte[] newSrc = replaceAll(src, "\n".getBytes(), "\r\n".getBytes()); assertEquals(newSrc, "\r\n\r\n text \r\n\r\n text".getBytes()); }
@Test public void shouldBeAbleToReplaceBytes() { final byte[] src = "\r\r text \r\r text \r\r text \r\r".getBytes(); final byte[] newSrc = replaceAll(src, "\r".getBytes(), "\n".getBytes()); assertEquals(newSrc, "\n\n text \n\n text \n\n text \n\n".getBytes()); }
@Test public void shouldNotReplaceBytesIfTargetBytesWereNotFound() { final byte[] src = "\n\n text \n\n text".getBytes(); final byte[] newSrc = replaceAll(src, "\r\n".getBytes(), "\n".getBytes()); assertEquals(newSrc, "\n\n text \n\n text".getBytes()); }