code: @Nullable
      public static String escape(@CheckForNull String text) {
          if (text==null)     return null;
          StringBuilder buf = new StringBuilder(text.length()+64);
          for( int i=0; i<text.length(); i++ ) {
              char ch = text.charAt(i);
              if(ch=='\n')
                  buf.append("<br>");
              else
              if(ch=='<')
                  buf.append("&lt;");
              else
              if(ch=='>')
                  buf.append("&gt;");
              else
              if(ch=='&')
                  buf.append("&amp;");
              else
              if(ch=='"')
                  buf.append("&quot;");
              else
              if(ch=='\'')
                  buf.append("&#039;");
              else
              if(ch==' ') {
                  // All spaces in a block of consecutive spaces are converted to
                  // non-breaking space (&nbsp;) except for the last one.  This allows
                  // significant whitespace to be retained without prohibiting wrapping.
                  char nextCh = i+1 < text.length() ? text.charAt(i+1) : 0;
                  buf.append(nextCh==' ' ? "&nbsp;" : " ");
              }
              else
                  buf.append(ch);
          }
          return buf.toString();
      }
docs: Escapes HTML unsafe characters like &lt;, &amp; to the respective character entities.