1 package emissary.util.web;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5
6
7
8
9 public class HtmlEscaper {
10
11 private static final byte[] LT_BYTES = "<".getBytes();
12 private static final byte[] GT_BYTES = ">".getBytes();
13 private static final byte[] AMPERSAND_BYTES = "&".getBytes();
14
15
16
17
18
19
20
21 public static byte[] escapeHtml(final byte[] theData) {
22 byte[] escaped = null;
23
24 try (ByteArrayOutputStream output = new ByteArrayOutputStream(theData.length)) {
25 for (int i = 0; i < theData.length; i++) {
26 if (theData[i] == '<') {
27 output.write(LT_BYTES);
28 } else if (theData[i] == '>') {
29 output.write(GT_BYTES);
30 } else if (theData[i] == '&') {
31 output.write(AMPERSAND_BYTES);
32 } else {
33 output.write(theData[i]);
34 }
35 }
36 escaped = output.toByteArray();
37
38 } catch (IOException ignored) {
39
40 }
41
42 return escaped;
43 }
44
45
46
47
48
49
50
51 public static String escapeHtml(final String s) {
52 return new String(escapeHtml(s.getBytes()));
53 }
54
55
56 private HtmlEscaper() {}
57 }