(String str, String... allowedTags)
| 47 | } |
| 48 | |
| 49 | public static String escape(String str, String... allowedTags) { |
| 50 | Pattern tagPattern = compileTagPattern(allowedTags); |
| 51 | StringBuilder ret = null; |
| 52 | int retEnd = 0; |
| 53 | |
| 54 | for (int i = 0, max = str.length(); i < max; i++) { |
| 55 | char c = str.charAt(i); |
| 56 | |
| 57 | if (c == '<' || c == '>' || c == '&') { |
| 58 | if (ret == null) ret = new StringBuilder(max * 2); |
| 59 | |
| 60 | if (c == '<' && allowedTags != null) { |
| 61 | int pos = str.substring(i, str.length()).indexOf('>'); |
| 62 | |
| 63 | if (tagPattern.matcher(str.substring(i, i + pos + 1)).find()) { |
| 64 | // Skip ahead to after the tag |
| 65 | i += pos; |
| 66 | continue; |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | ret.append(str, retEnd, i); |
| 71 | |
| 72 | if (c == '<') { |
| 73 | ret.append("<"); |
| 74 | } else if (c == '>') { |
| 75 | ret.append(">"); |
| 76 | } else { |
| 77 | ret.append("&"); |
| 78 | } |
| 79 | |
| 80 | retEnd = i + 1; |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | if (ret == null) { |
| 85 | return str; |
| 86 | } else { |
| 87 | ret.append(str, retEnd, str.length()); |
| 88 | |
| 89 | return ret.toString(); |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | private static Pattern compileTagPattern(String... tags) { |
| 94 | StringBuilder builder = new StringBuilder(); |
no test coverage detected