Converts the raw characters to XML escape characters.

@param rawContent
@param charset Null when charset is not known, so we assume it's unicode
@param isNoLines
@return escape string
341678
public static String escapeXML(String rawContent, String charset, boolean isNoLines) {
		if (rawContent == null)
			return "";
		else {
			StringBuffer sb = new StringBuffer();

			for (int i = 0; i < rawContent.length(); i++) {
				char ch = rawContent.charAt(i);
				if (ch == '\'')
					sb.append("&#39;");
				else if (ch == '&')
					sb.append("&amp;");
				else if (ch == '"')
					sb.append("&quot;");
				else if (ch == '<')
					sb.append("&lt;");
				else if (ch == '>')
					sb.append("&gt;");
				else if (ch > '~' && charset != null && charSetImpliesAscii(charset)) 
					// TODO - why is hashcode the only way to get the unicode number for the character
					// in jre 5.0?
					sb.append("&#x"+Integer.toHexString(ch).toUpperCase()+";");
				else if (isNoLines) {
					if (ch == '\r')
						sb.append("&#xA;");
					else if (ch != '\n')
						sb.append(ch);
				}
				else
					sb.append(ch);
			}
			return sb.toString();
		}
	}
594627
public static String escapeForXML(String inString) {
    if (inString == null)
      return null;
    String outString = inString;
    outString = replace(outString, "&", "&amp;");
    outString = replace(outString, "<", "&lt;");
    outString = replace(outString, ">", "&gt;");
    outString = replace(outString, "\"", "&quot;");
    outString = replace(outString, "'", "&apos;");
    // We'll escape all chars not in this set (Safe)
    String validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 &#;-_=+:,.?/";
    for (int i = 0; i < outString.length(); i++) {
      char c = outString.charAt(i);
      if (validChars.indexOf(c) == -1) {
        // Escape the character
        outString = replace(outString, "" + c, "&#" + ((int) c) + ";");
      }
    }
    return outString;
  }
1198690
public static String encode(String value, Charset charset) {
		try {
			return URLEncoder.encode(value, charset.name());
		}
		catch (UnsupportedEncodingException ex) {
			throw new IllegalArgumentException("Characterset is not supported.");
		}
	}
777180
public static String escape(String string, char escape, boolean isPath)
   {
      try
      {
         BitSet validChars = isPath ? URISaveEx : URISave;
         byte[] bytes = string.getBytes("utf-8");
         StringBuffer out = new StringBuffer(bytes.length);
         for (int i = 0; i < bytes.length; i++)
         {
            int c = bytes[i] & 0xff;
            if (validChars.get(c) && c != escape)
            {
               out.append((char)c);
            }
            else
            {
               out.append(escape);
               out.append(hexTable[(c >> 4) & 0x0f]);
               out.append(hexTable[(c) & 0x0f]);
            }
         }
         return out.toString();
      }
      catch (Exception exc)
      {
         throw new InternalError(exc.toString());
      }
   }
905849
static void escape(final char[] text, final int offset, final int len, final Writer writer,
                       final XmlEscapeSymbols symbols,
                       final XmlEscapeType escapeType, final XmlEscapeLevel escapeLevel)
                       throws IOException {

        if (text == null || text.length == 0) {
            return;
        }

        final int level = escapeLevel.getEscapeLevel();
        final boolean useCERs = escapeType.getUseCERs();
        final boolean useHexa = escapeType.getUseHexa();

        final int max = (offset + len);

        int readOffset = offset;

        for (int i = offset; i < max; i++) {

            final int codepoint = Character.codePointAt(text, i);


            boolean codepointValid = symbols.CODEPOINT_VALIDATOR.isValid(codepoint);


            /*
             * Shortcut: most characters will be ASCII/Alphanumeric, and we won't need to do anything at
             * all for them
             */
            if (codepoint <= (XmlEscapeSymbols.LEVELS_LEN - 2)
                    && level < symbols.ESCAPE_LEVELS[codepoint]
                    && codepointValid) {
                continue;
            }


            /*
             * Shortcut: we might not want to escape non-ASCII chars at all either.
             */
            if (codepoint > (XmlEscapeSymbols.LEVELS_LEN - 2)
                    && level < symbols.ESCAPE_LEVELS[XmlEscapeSymbols.LEVELS_LEN - 1]
                    && codepointValid) {

                if (Character.charCount(codepoint) > 1) {
                    // This is to compensate that we are actually reading two char[] positions with a single codepoint.
                    i++;
                }

                continue;

            }


            /*
             * At this point we know for sure we will need some kind of escape, so we
             * can write all the contents pending up to this point.
             */

            if (i - readOffset > 0) {
                writer.write(text, readOffset, (i - readOffset));
            }

            if (Character.charCount(codepoint) > 1) {
                // This is to compensate that we are actually escaping two char[] positions with a single codepoint.
                i++;
            }

            readOffset = i + 1;


            /*
             * If the char is invalid, there is nothing to write, simply skip it (which we already did by
             * incrementing the readOffset.
             */
            if (!codepointValid) {
                continue;
            }


            /*
             * -----------------------------------------------------------------------------------------
             *
             * Perform the real escape, attending the different combinations of NCR, DCR and HCR needs.
             *
             * -----------------------------------------------------------------------------------------
             */

            if (useCERs) {
                // We will try to use a CER

                final int codepointIndex =
                        Arrays.binarySearch(symbols.SORTED_CODEPOINTS, codepoint);

                if (codepointIndex >= 0) {
                    // CER found! just write it and go for the next char
                    writer.write(symbols.SORTED_CERS_BY_CODEPOINT[codepointIndex]);
                    continue;
                }

            }

            /*
             * No NCR-escape was possible (or allowed), so we need decimal/hexa escape.
             */

            if (useHexa) {
                writer.write(REFERENCE_HEXA_PREFIX);
                writer.write(Integer.toHexString(codepoint));
            } else {
                writer.write(REFERENCE_DECIMAL_PREFIX);
                writer.write(String.valueOf(codepoint));
            }
            writer.write(REFERENCE_SUFFIX);

        }


        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: append the remaining unescaped text to the writer and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (max - readOffset > 0) {
            writer.write(text, readOffset, (max - readOffset));
        }

    }
1354729
public String readStringNullEnd(final Charset charset) {
    int initialPosition = position;
    int cnt = 0;
    while (remaining() > 0 && (buf[position++] != 0)) {
      cnt++;
    }
    return new String(buf, initialPosition, cnt, charset);
  }
881159
public static String encodeString(String string, Charset charset) {
        if (charset == null)
            charset = ENCODING;
        byte[] bytes = null;
        bytes = string.getBytes(charset);

        int len = bytes.length;
        byte[] encoded = new byte[bytes.length * 3];
        int n = 0;
        boolean noEncode = true;

        for (int i = 0; i < len; i++) {
            byte b = bytes[i];

            if (b == ' ') {
                noEncode = false;
                encoded[n++] = (byte) '+';
            } else if (b >= 'a' && b <= 'z' ||
                    b >= 'A' && b <= 'Z' ||
                    b >= '0' && b <= '9') {
                encoded[n++] = b;
            } else {
                noEncode = false;
                encoded[n++] = (byte) '%';
                byte nibble = (byte) ((b & 0xf0) >> 4);
                if (nibble >= 10)
                    encoded[n++] = (byte) ('A' + nibble - 10);
                else
                    encoded[n++] = (byte) ('0' + nibble);
                nibble = (byte) (b & 0xf);
                if (nibble >= 10)
                    encoded[n++] = (byte) ('A' + nibble - 10);
                else
                    encoded[n++] = (byte) ('0' + nibble);
            }
        }

        if (noEncode)
            return string;

        return new String(encoded, 0, n, charset);
    }
1058578
public Charset charset(Charset defaultValue) {
        return charset != null ? Charset.forName(charset) : defaultValue;
    }
130364
public static Content content(String somePlainText) {
		Content c = null;
		try {
			c = new Content("text/plain; charset=UTF-8", somePlainText.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) { /* UTF-8 is never unsupported */
		}
		return c;
	}
239228
public static String encodeIllegalXMLCharacters(String text)
   {
      if (text == null)
      {
         throw new IllegalArgumentException("null argument");
      }
      StringBuilder buf = null;
      int length = text.length();
      int pos = 0;
      for (int i = 0; i < length; i++)
      {
         int ch = text.charAt(i);
         switch (ch)
         {
            case '<' :
            case '>' :
            case '&' :
            case '"' :
            case '\'' :
               if (buf == null)
               {
                  buf = new StringBuilder();
               }
               if (i > 0)
               {
                  buf.append(text.substring(pos, i));
               }
               pos = i + 1;
               break;
            default :
               continue;
         }
         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("&apos;");
         }
      }
      if (buf == null)
      {
         return text;
      }
      else
      {
         if (pos < length)
         {
            buf.append(text.substring(pos));
         }
         return buf.toString();
      }
   }
973085
public static String inputStream2String(final InputStream is, final String charsetName) {
        if (is == null || isSpace(charsetName)) return null;
        try {
            return new String(inputStream2Bytes(is), charsetName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
605153
public static String decode(String content, Charset charset) {
		if (null == charset) {
			charset = CharsetUtil.defaultCharset();
		}
		return decode(content, charset.name());
	}
828574
protected String escapeXmlSpecialCharacters(String url) {
		// https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents
		return url
				.replace("&", "&amp;") // must be escaped first!!!
				.replace("\"", "&quot;")
				.replace("'", "&apos;")
				.replace("<", "&lt;")
				.replace(">", "&gt;");
	}
583565
public static String addCharset(String charset, String contentType)
    {
        if (null == contentType)
        {
            return "text/plain;charset=" + charset;
        }
        else
        {
            Matcher matcher = CHARSET_PATT.matcher(contentType);
            if (matcher.find())
            {
                // replace what ever content-type with the charset
                return contentType.substring(0, matcher.start(1)) +
                    charset + contentType.substring(matcher.end(1));
            }
            else
            {
                return contentType + ";charset=" + charset;
            }
        }
    }
868344
@VisibleForTesting
  static String icuEscape(String rawText) {

    Matcher matcher = ICU_SYNTAX_CHAR_NEEDING_ESCAPE_PATTERN.matcher(rawText);
    if (!matcher.find()) {
      return rawText;
    }

    StringBuffer escapedTextSb = new StringBuffer();
    do {
      String repl = ICU_SYNTAX_CHAR_ESCAPE_MAP.get(matcher.group());
      matcher.appendReplacement(escapedTextSb, repl);
    } while (matcher.find());
    matcher.appendTail(escapedTextSb);
    return escapedTextSb.toString();
  }
914139
public function escape($string, $charset=null) {

        if (\is_null($charset)){
            $charset = $this['charset'];
        }

        return \htmlspecialchars($string, \ENT_QUOTES, $charset);
    }
173237
public static String escapeHtml(String s)
  {
    if (s == null)
      return null;

    StringBuilder cb = new StringBuilder();
    int lineCharacter = 0;
    boolean startsWithSpace = false;
    
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);

      lineCharacter++;
      
      if (ch == '<')
        cb.append("&lt;");
      else if (ch == '&')
        cb.append("&amp;");
      else if (ch == '\n' || ch == '\r') {
        lineCharacter = 0;
        cb.append(ch);
        startsWithSpace = false;
      }
      else if (lineCharacter > 70 && ch == ' ' && ! startsWithSpace) {
        lineCharacter = 0;
        cb.append('\n');
        for (; i + 1 < s.length() && s.charAt(i + 1) == ' '; i++) {
        }
      }
      else if (lineCharacter == 1 && (ch == ' ' || ch == '\t')) {
        cb.append((char) ch);
        startsWithSpace = true;
      }
      else
        cb.append(ch);
    }

    return cb.toString();
  }