View Javadoc
1   package emissary.util.web;
2   
3   import java.io.ByteArrayOutputStream;
4   import java.io.IOException;
5   
6   /**
7    * Methods for dealing with escaped HTML as bytes and strings
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       * encode greater than, less than, and ampersand characters in a byte arroy.
17       * 
18       * @param theData input bytes
19       * @return a copy of the input byte array with specific characters encoded.
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              /* dont care */
40          }
41  
42          return escaped;
43      }
44  
45      /**
46       * Escape html string
47       * 
48       * @param s the input string
49       * @return the escaped string
50       */
51      public static String escapeHtml(final String s) {
52          return new String(escapeHtml(s.getBytes()));
53      }
54  
55      /** This class is not meant to be instantiated. */
56      private HtmlEscaper() {}
57  }