01: package com.mockrunner.example.tag;
02:
03: import java.io.IOException;
04: import java.io.StringWriter;
05: import java.util.regex.Matcher;
06: import java.util.regex.Pattern;
07:
08: import javax.servlet.jsp.JspException;
09: import javax.servlet.jsp.tagext.SimpleTagSupport;
10:
11: /**
12: * The purpose of this simple tag is to filter images. If its
13: * body contains HTML image tags of the form
14: * <pre>
15: * <img src="URL">
16: * </pre>
17: * it replaces the URL with <i>dummy.jpg</i>.
18: * Image filtering can be enabled or disabled by setting the <i>filter</i>
19: * attribute. Of course this attribute can be set dynamically with the help
20: * of an EL or scripting expression.
21: */
22: public class FilterImagesTag extends SimpleTagSupport {
23: private final static Pattern pattern = Pattern
24: .compile("<\\s*img[^<>]+src\\s*=\\s*\"[^<>]*\".*?>");
25:
26: private boolean doFilter = false;
27:
28: public void setFilter(boolean doFilter) {
29: this .doFilter = doFilter;
30: }
31:
32: public void doTag() throws JspException, IOException {
33: if (!doFilter) {
34: getJspBody().invoke(null);
35: } else {
36: StringWriter writer = new StringWriter();
37: getJspBody().invoke(writer);
38: writer.flush();
39: String filteredBody = doFilter(writer.toString());
40: getJspContext().getOut().print(filteredBody);
41: }
42: }
43:
44: private String doFilter(String body) {
45: Matcher matcher = pattern.matcher(body);
46: StringBuffer output = new StringBuffer();
47: while (matcher.find()) {
48: String match = matcher.group();
49: match = match.replaceFirst("src.*=.*\".*\"",
50: "src=\"dummy.jpg\"");
51: matcher.appendReplacement(output, match);
52: }
53: matcher.appendTail(output);
54: return output.toString();
55: }
56: }
|