HtmlEscaper.java

  1. package emissary.util.web;

  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;

  4. /**
  5.  * Methods for dealing with escaped HTML as bytes and strings
  6.  */
  7. public class HtmlEscaper {

  8.     private static final byte[] LT_BYTES = "<".getBytes();
  9.     private static final byte[] GT_BYTES = ">".getBytes();
  10.     private static final byte[] AMPERSAND_BYTES = "&".getBytes();

  11.     /**
  12.      * encode greater than, less than, and ampersand characters in a byte arroy.
  13.      *
  14.      * @param theData input bytes
  15.      * @return a copy of the input byte array with specific characters encoded.
  16.      */
  17.     public static byte[] escapeHtml(final byte[] theData) {
  18.         byte[] escaped = null;

  19.         try (ByteArrayOutputStream output = new ByteArrayOutputStream(theData.length)) {
  20.             for (int i = 0; i < theData.length; i++) {
  21.                 if (theData[i] == '<') {
  22.                     output.write(LT_BYTES);
  23.                 } else if (theData[i] == '>') {
  24.                     output.write(GT_BYTES);
  25.                 } else if (theData[i] == '&') {
  26.                     output.write(AMPERSAND_BYTES);
  27.                 } else {
  28.                     output.write(theData[i]);
  29.                 }
  30.             }
  31.             escaped = output.toByteArray();

  32.         } catch (IOException iox) {
  33.             /* dont care */
  34.         }

  35.         return escaped;
  36.     }

  37.     /**
  38.      * Escape html string
  39.      *
  40.      * @param s the input string
  41.      * @return the escaped string
  42.      */
  43.     public static String escapeHtml(final String s) {
  44.         return new String(escapeHtml(s.getBytes()));
  45.     }

  46.     /** This class is not meant to be instantiated. */
  47.     private HtmlEscaper() {}
  48. }