Escapes HTML/XML unsafe characters for the PCDATA section.
This method does not handle whitespace-preserving escape, nor attribute escapes.
979071
public static String escape(String v) {
        if (v==null)    return null;

        StringBuilder buf = new StringBuilder(v.length()+64);
        for( int i=0; i<v.length(); i++ ) {
            char ch = v.charAt(i);
            if(ch=='<')
                buf.append("&lt;");
            else
            if(ch=='>')
                buf.append("&gt;");
            else
            if(ch=='&')
                buf.append("&amp;");
            else
                buf.append(ch);
        }
        if (buf.length()==v.length())   return  v;  // unmodified
        return buf.toString();
    }
24588
public String[] escape(String name, String[] values) {

        if (values == null) {
            return null;
        }
        if (m_exceptions.contains(name)) {
            return values;
        }
        boolean cleanHtml = m_cleanHtml.contains(name);
        String[] result = new String[values.length];
        for (int i = 0; i < values.length; i++) {
            if (cleanHtml) {
                result[i] = filterAntiSamy(values[i]);
            } else {
                result[i] = CmsEncoder.escapeXml(values[i]);
            }
        }
        return result;
    }
277195
public static String escapeForXML(String str) {
        StringBuilder sb = new StringBuilder(str.length());

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);

            boolean foundEscape = false;
            for (int j = 0; j < toBeEscaped.length; j++) {
                if (c == toBeEscaped[j]) {
                    sb.append(escaped[j]);
                    foundEscape = true;
                    break;
                }
            }

            if (!foundEscape) {
                sb.append(c);
            }
        }
        return sb.toString();
    }
16223
static String escape(final String text, final HtmlEscapeType escapeType, final HtmlEscapeLevel escapeLevel) {

        if (text == null) {
            return null;
        }

        final int level = escapeLevel.getEscapeLevel();
        final boolean useHtml5 = escapeType.getUseHtml5();
        final boolean useNCRs = escapeType.getUseNCRs();
        final boolean useHexa = escapeType.getUseHexa();

        final HtmlEscapeSymbols symbols =
                (useHtml5? HtmlEscapeSymbols.HTML5_SYMBOLS : HtmlEscapeSymbols.HTML4_SYMBOLS);

        StringBuilder strBuilder = null;

        final int offset = 0;
        final int max = text.length();

        int readOffset = offset;

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

            final char c = text.charAt(i);


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


            /*
             * Shortcut: we might not want to escape non-ASCII chars at all either.
             */
            if (c > HtmlEscapeSymbols.MAX_ASCII_CHAR
                    && level < symbols.ESCAPE_LEVELS[HtmlEscapeSymbols.MAX_ASCII_CHAR + 1]) {
                continue;
            }


            /*
             * Compute the codepoint. This will be used instead of the char for the rest of the process.
             */
            final int codepoint = Character.codePointAt(text, i);


            /*
             * At this point we know for sure we will need some kind of escape, so we
             * can increase the offset and initialize the string builder if needed, along with
             * copying to it all the contents pending up to this point.
             */

            if (strBuilder == null) {
                strBuilder = new StringBuilder(max + 20);
            }

            if (i - readOffset > 0) {
                strBuilder.append(text, readOffset, i);
            }

            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;


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

            if (useNCRs) {
                // We will try to use an NCR

                if (codepoint < symbols.NCRS_BY_CODEPOINT_LEN) {
                    // codepoint < 0x2fff - all HTML4, most HTML5

                    final short ncrIndex = symbols.NCRS_BY_CODEPOINT[codepoint];
                    if (ncrIndex != symbols.NO_NCR) {
                        // There is an NCR for this codepoint!
                        strBuilder.append(symbols.SORTED_NCRS[ncrIndex]);
                        continue;
                    } // else, just let it exit the block and let decimal/hexa escape do its job

                } else if (symbols.NCRS_BY_CODEPOINT_OVERFLOW != null) {
                    // codepoint >= 0x2fff. NCR, if exists, will live at the overflow map (if there is one).

                    final Short ncrIndex = symbols.NCRS_BY_CODEPOINT_OVERFLOW.get(Integer.valueOf(codepoint));
                    if (ncrIndex != null) {
                        strBuilder.append(symbols.SORTED_NCRS[ncrIndex.shortValue()]);
                        continue;
                    } // else, just let it exit the block and let decimal/hexa escape do its job

                }

            }

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

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

        }


        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: return the original String object if no escape was actually needed. Otherwise
         *                 append the remaining unescaped text to the string builder and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (strBuilder == null) {
            return text;
        }

        if (max - readOffset > 0) {
            strBuilder.append(text, readOffset, max);
        }

        return strBuilder.toString();

    }
1317840
def _safe_attr(attr, camel_killer=False, replacement_char='x'):
    """"""
    allowed = string.ascii_letters + string.digits + '_'

    attr = _safe_key(attr)

    if camel_killer:
        attr = _camel_killer(attr)

    attr = attr.replace(' ', '_')

    out = ''
    for character in attr:
        out += character if character in allowed else "_"
    out = out.strip("_")

    try:
        int(out[0])
    except (ValueError, IndexError):
        pass
    else:
        out = '{0}{1}'.format(replacement_char, out)

    if out in kwlist:
        out = '{0}{1}'.format(replacement_char, out)

    return re.sub('_+', '_', out)
1024905
private void escape(String value) {
        int n = value.length();
        int i = 0;
        for (int j = 0; j < n; ++j) {
            char c = value.charAt(j);
            int k = ESCAPED_CHARS.indexOf(c);
            if (k >= 0 || c < ' ') {
                if (i < j) {
                    append(value, i, j);
                }
                if (k >= 0) {
                    append(ESCAPE_SEQ[k]);
                } else {
                    append("\\u");
                    append(String.format("%04x", Integer.valueOf(c)));
                }
                i = j + 1;
            }
        }
        if (i < n) {
            append(value, i, n);
        }
    }
1128886
def escape(data):
        

        escaped_data = b""
        for byte in data:
            if intToByte(byteToInt(byte)) in APIFrame.ESCAPE_BYTES:
                escaped_data += APIFrame.ESCAPE_BYTE
                escaped_data += intToByte(0x20 ^ byteToInt(byte))
            else:
                escaped_data += intToByte(byteToInt(byte))

        return escaped_data
898944
function escape_data(&$value){
    // quick fix for ' character
    /** @todo have a proper function escaping all these */
    if(is_string($value)){
        $value = htmlspecialchars_decode($value);
        $value = self::strip_html_tags($value);
        $value = htmlentities($value);
        $value = stripslashes($value);
        $value = preg_replace('/\'/','´', $value);
        $value = addslashes($value);
        pr($value);
    }
  }
1038613
public static String escapeAttributeValue(String s) {
        s = cleanWS(s);
        s = replaceAll(s, BackSlashPtn, EscBackSlash);
        s = replaceAll(s, SemicolonPtn, EscSemicolon);
        s = replaceAll(s, RParenPtn, EscRParen);
        return s;
    }
269370
private static String unescapeHtml(final String input) {
        StringBuilder writer = null;
        int len = input.length();
        int i = 1;
        int st = 0;
        while (true) {
            // look for '&'
            while (i < len && input.charAt(i-1) != '&') {
                i++;
            }
            if (i >= len) {
                break;
            }

            // found '&', look for ';'
            int j = i;
            while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';') {
                j++;
            }
            if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) {
                i++;
                continue;
            }

            // found escape
            if (input.charAt(i) == '#') {
                // numeric escape
                int k = i + 1;
                int radix = 10;

                final char firstChar = input.charAt(k);
                if (firstChar == 'x' || firstChar == 'X') {
                    k++;
                    radix = 16;
                }

                try {
                    int entityValue = Integer.parseInt(input.substring(k, j), radix);

                    if (writer == null) {
                        writer = new StringBuilder(input.length());
                    }
                    writer.append(input.substring(st, i - 1));

                    if (entityValue > 0xFFFF) {
                        final char[] chrs = Character.toChars(entityValue);
                        writer.append(chrs[0]);
                        writer.append(chrs[1]);
                    }
                    else if(entityValue == 39) {
                        writer.append('\'');
                    }
                    else {
                        writer.append(entityValue);
                    }

                }
                catch (NumberFormatException ex) {
                    i++;
                    continue;
                }
            }
            else {
                // named escape
                CharSequence value = LOOKUP_MAP.get(input.substring(i, j));
                if (value == null) {
                    i++;
                    continue;
                }

                if (writer == null) {
                    writer = new StringBuilder(input.length());
                }
                writer.append(input.substring(st, i - 1));

                writer.append(value);
            }

            // skip escape
            st = j + 1;
            i = st;
        }

        if (writer != null) {
            writer.append(input.substring(st, len));
            return writer.toString();
        }
        return input;
    }
500309
private String escapeAttributeNameSpecialCharacters(String str)
    {
        if (str != null)
        {
            StringBuffer strBuf = new StringBuffer("");

            for (int i = 0; i < str.length(); i++)
            {
                char strChar = str.charAt(i);

                switch (strChar)
                {
                    case ':':
                        {
                            strBuf.append("_ns-sep_");
                            break;
                        }
                    default:
                        {
                            strBuf.append(strChar);
                            break;
                        }
                }
            }
            str = strBuf.toString();
        }
        return str;
    }
548936
public function xml_escape($string) {
        if (!empty($string) && htmlspecialchars($string) != $string) {
            // If the string contains something that looks like the end
            // of a CDATA section, then we need to avoid errors by splitting
            // the string between two CDATA sections.
            $string = str_replace(']]>', ']]]]><![CDATA[>', $string);
            return "<![CDATA[{$string}]]>";
        } else {
            return $string;
        }
    }
175281
private static String escapeXml(String input) {
        return input == null ? "" : input.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
    }
236251
public static String escapeHtml(String htmlString) {
		StringBuffer sb = new StringBuffer(htmlString.length());
		// true if last char was blank
		boolean lastWasBlankChar = false;
		int len = htmlString.length();
		char c;

		for (int i = 0; i < len; i++)
		{
			c = htmlString.charAt(i);
			if (c == ' ') {
				// blank gets extra work,
				// this solves the problem you get if you replace all
				// blanks with &nbsp;, if you do that you loss
				// word breaking
				if (lastWasBlankChar) {
					lastWasBlankChar = false;
					sb.append("&nbsp;");
				}
				else {
					lastWasBlankChar = true;
					sb.append(' ');
				}
			}
			else {
				lastWasBlankChar = false;
				//
				// HTML Special Chars
				if (c == '"')
					sb.append("&quot;");
				else if (c == '&')
					sb.append("&amp;");
				else if (c == '<')
					sb.append("&lt;");
				else if (c == '>')
					sb.append("&gt;");
				else if (c == '/')
					sb.append("-");
				else if (c == '\\')
					sb.append("-");
				else if (c == '\n')
					// Handle Newline
					sb.append("&lt;br/&gt;");
				else {
					int ci = 0xffff & c;
					if (ci < 160 )
						// nothing special only 7 Bit
						sb.append(c);
					else {
						// Not 7 Bit use the unicode system
						sb.append("&#");
						sb.append(String.valueOf(ci));
						sb.append(';');
					}
				}
			}
		}
		return sb.toString();
	}
670367
def quote_xml(text):
    
    text = _coerce_unicode(text)

    # If it's a CDATA block, return the text as is.
    if text.startswith(CDATA_START):
        return text

    # If it's not a CDATA block, escape the XML and return the character
    # encoded string.
    return saxutils.escape(text)
824435
public static String escapeXML(final char[] chars, final int offset, final int length) {
        final StringBuilder escaped = new StringBuilder();

        final int end = offset + length;
        for (int i = offset; i < end; ++i) {
            final char c = chars[i];

            switch (c) {
            case '\'':
                escaped.append("&apos;");
                break;
            case '\"':
                escaped.append("&quot;");
                break;
            case '<':
                escaped.append("&lt;");
                break;
            case '>':
                escaped.append("&gt;");
                break;
            case '&':
                escaped.append("&amp;");
                break;
            default:
                escaped.append(c);
            }
        }

        return escaped.toString();
    }
1010030
@Override
	public void escape() throws IOException {
		LOG.debug("...ContentEscape escape()");

		if (contentAccess == null) {
			LOG.warn("No content to output");
		} else {
			String mimeType = contentAccess.getMimeType();

			Response response = getResponse();
			response.setContentType(mimeType);

			if (isCacheable()) {
				getResponse().setHeader("Cache-Control", CacheType.CONTENT_CACHE.getSettings());
			} else {
				getResponse().setHeader("Cache-Control", CacheType.CONTENT_NO_CACHE.getSettings());
			}

			if (contentAccess.getDescription() != null) {
				String fileName = WebUtilities.encodeForContentDispositionHeader(contentAccess.
						getDescription());

				if (displayInline) {
					response.setHeader("Content-Disposition", "inline; filename=" + fileName);
				} else {
					response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
				}
			}

			if (contentAccess instanceof ContentStreamAccess) {
				InputStream stream = null;

				try {
					stream = ((ContentStreamAccess) contentAccess).getStream();

					if (stream == null) {
						throw new SystemException(
								"ContentAccess returned null stream, access=" + contentAccess);
					}

					StreamUtil.copy(stream, response.getOutputStream());
				} finally {
					StreamUtil.safeClose(stream);
				}
			} else {
				byte[] bytes = contentAccess.getBytes();

				if (bytes == null) {
					throw new SystemException(
							"ContentAccess returned null data, access=" + contentAccess);
				}

				response.getOutputStream().write(bytes);
			}
		}
	}