private void replace(Reader in, Writer out, boolean refs) throws IOException { final String template = IoUtils.read(in); final Matcher matcher = refStart.matcher(template); int matchPos = 0; int appendPos = 0; while (matcher.find(matchPos)) { final String name = matcher.group(1); if (!snippets.containsKey(name)) { throw new IllegalArgumentException("Snippet '" + name + "' not defined."); } if (refs) { out.write(template.substring(appendPos, matcher.start())); matchPos = appendPos = matcher.end(); } else { out.write(template.substring(appendPos, matcher.end())); appendPos = template.indexOf(refEnd, matcher.end()); if (appendPos < 0) { throw new IllegalArgumentException( "No refEnd marker found for refStart '" + template.substring(matcher.start(), matcher.end()) + "'"); } matchPos = appendPos + refEnd.length(); } out.write(prefix); out.write(snippets.get(name)); out.write(postfix); } out.write(template.substring(appendPos)); }
private Map<String, String> parse(Reader in, Map<String, String> snippets) throws IOException { final String code = IoUtils.read(in); final Matcher matcher = snippetStart.matcher(code); int endPos = 0; while (matcher.find(endPos)) { endPos = code.indexOf(snippetEnd, matcher.end()); if (endPos < 0) { throw new IllegalArgumentException( "No snippetEnd marker found for snippetStart '" + code.substring(matcher.start(), matcher.end()) + "'"); } final String name = matcher.group(1); if (snippets.containsKey(name)) { throw new IllegalArgumentException("Snippet with name '" + name + "' already existing."); } snippets.put(name, trim(code.substring(matcher.end(), endPos))); endPos += snippetEnd.length(); } return snippets; }