Java Code Examples for org.apache.commons.text.StringEscapeUtils#escapeXml11()

The following examples show how to use org.apache.commons.text.StringEscapeUtils#escapeXml11() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Dom4j.java    From cuba with Apache License 2.0 6 votes vote down vote up
public static void storeMap(Element parentElement, Map<String, String> map) {
    if (map == null) {
        return;
    }

    Element mapElem = parentElement.addElement("map");
    for (Map.Entry<String, String> entry : map.entrySet()) {
        Element entryElem = mapElem.addElement("entry");
        entryElem.addAttribute("key", entry.getKey());
        Element valueElem = entryElem.addElement("value");
        if (entry.getValue() != null) {
            String value = StringEscapeUtils.escapeXml11(entry.getValue());
            valueElem.setText(value);
        }
    }
}
 
Example 2
Source File: TokenSerializer.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
public String serialize(RequestContext context, Element rpToken) {
    if (rpToken != null) {
        StringWriter sw = new StringWriter();
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            try {
                tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
                tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
            } catch (IllegalArgumentException ex) {
                // ignore
            }

            Transformer t = tf.newTransformer();
            t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            t.transform(new DOMSource(rpToken), new StreamResult(sw));
        } catch (TransformerException te) {
            LOG.warn("nodeToString Transformer Exception");
        }
        String serializedToken = sw.toString();

        return StringEscapeUtils.escapeXml11(serializedToken);
    }

    return null;
}
 
Example 3
Source File: FlowFilePackagerV1.java    From nifi with Apache License 2.0 6 votes vote down vote up
private void writeAttributesEntry(final Map<String, String> attributes, final TarArchiveOutputStream tout) throws IOException {
    final StringBuilder sb = new StringBuilder();
    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE properties\n  SYSTEM \"http://java.sun.com/dtd/properties.dtd\">\n");
    sb.append("<properties>");
    for (final Map.Entry<String, String> entry : attributes.entrySet()) {
        final String escapedKey = StringEscapeUtils.escapeXml11(entry.getKey());
        final String escapedValue = StringEscapeUtils.escapeXml11(entry.getValue());
        sb.append("\n  <entry key=\"").append(escapedKey).append("\">").append(escapedValue).append("</entry>");
    }
    sb.append("</properties>");

    final byte[] metaBytes = sb.toString().getBytes(StandardCharsets.UTF_8);
    final TarArchiveEntry attribEntry = new TarArchiveEntry(FILENAME_ATTRIBUTES);
    attribEntry.setMode(tarPermissions);
    attribEntry.setSize(metaBytes.length);
    tout.putArchiveEntry(attribEntry);
    tout.write(metaBytes);
    tout.closeArchiveEntry();
}
 
Example 4
Source File: Strings.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Escape XML entities and illegal characters in the given string. This
 * enhances the functionality of
 * org.apache.commons.lang.StringEscapeUtils.escapeXml by escaping
 * low-valued unprintable characters, which are not permitted by the W3C XML
 * 1.0 specification.
 *
 * @param s
 *            a string
 * @return the same string with characters not permitted by the XML
 *         specification escaped
 * @see <a href="http://www.w3.org/TR/REC-xml/#charsets">Extensible Markup
 *      Language (XML) 1.0 (Fifth Edition)</a>
 * @see <a
 *      href="http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)">org.apache.commons.lang.StringEscapeUtils
 *      javadoc</a>
 */
public static String escapeXml(String s) {
    initializeEscapeMap();

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

    char[] sChars = s.toCharArray();
    StringBuilder sb = new StringBuilder();
    int lastReplacement = 0;
    for (int i = 0; i < sChars.length; i++) {
        if (isInvalidXMLCharacter(sChars[i])) {
            // append intermediate string to string builder
            sb.append(sChars, lastReplacement, i - lastReplacement);
            // substitute control character with escape sequence
            sb.append(sChars[i] == 0xFFFE ? "\\ufffe" : xmlLowValueEscapeStrings[sChars[i]]);
            // advance last pointer past this character
            lastReplacement = i + 1;
        }
    }
    if (lastReplacement < sChars.length) {
        sb.append(sChars, lastReplacement, sChars.length - lastReplacement);
    }

    return StringEscapeUtils.escapeXml11(sb.toString());
}
 
Example 5
Source File: XSLTEntityHandler.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Serialises the rendered content of the RWiki Object to SAX
 * 
 * @param rwo
 * @param ch
 * @param withBreadCrumb 
 */
public void renderToXML(RWikiObject rwo, final ContentHandler ch, boolean withBreadCrumb, boolean escapeXML)
		throws SAXException, IOException
{

	String renderedPage;
	try
	{
		renderedPage = render(rwo,withBreadCrumb);
	}
	catch (Exception e)
	{
		renderedPage = Messages.getString("XSLTEntityHandler.32") + rwo.getName() + Messages.getString("XSLTEntityHandler.33") + e.getClass() + Messages.getString("XSLTEntityHandler.34") + e.getMessage(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		log.info(renderedPage, e);
	}
	String contentDigest = DigestHtml.digest(renderedPage);
	if (contentDigest.length() > 500)
	{
		contentDigest = contentDigest.substring(0, 500);
	}
	if (renderedPage == null || renderedPage.trim().length() == 0)
	{
		renderedPage = Messages.getString("XSLTEntityHandler.35"); //$NON-NLS-1$
	}
	if (contentDigest == null || contentDigest.trim().length() == 0)
	{
		contentDigest = Messages.getString("XSLTEntityHandler.36"); //$NON-NLS-1$
	}

	String cdataEscapedRendered = renderedPage
			.replaceAll("]]>", "]]>]]&gt;<![CDATA["); //$NON-NLS-1$ //$NON-NLS-2$
	String cdataContentDigest = contentDigest.replaceAll("]]>", "]]>]]&gt;<![CDATA["); //$NON-NLS-1$ //$NON-NLS-2$

       /* http://jira.sakaiproject.org/browse/SAK-13281
        * ensure all page content is escaped or double escaped before it goes into the parser,
        * if this is not done then the parser will unescape html entities during processing
        */		
       renderedPage = "<content><rendered>" + (escapeXML ? StringEscapeUtils.escapeXml11(renderedPage) : renderedPage) //$NON-NLS-1$
			+ "</rendered><rendered-cdata><![CDATA[" + cdataEscapedRendered + "]]></rendered-cdata><contentdigest><![CDATA[" + cdataContentDigest //$NON-NLS-1$ //$NON-NLS-2$
			+ "]]></contentdigest></content>"; //$NON-NLS-1$

	try
	{
		parseToSAX(renderedPage, ch);
	}
	catch (SAXException ex)
	{
		SimpleCoverage.cover("Failed to parse renderedPage from " + rwo.getName()); //$NON-NLS-1$
		Attributes dummyAttributes = new AttributesImpl();
		ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
				SchemaNames.EL_NSERROR, dummyAttributes);
		ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
				SchemaNames.EL_NSERRORDESC, dummyAttributes);
		String s = Messages.getString("XSLTEntityHandler.46") //$NON-NLS-1$
				+ ex.getMessage();
		ch.characters(s.toCharArray(), 0, s.length());
		ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
				SchemaNames.EL_NSERRORDESC);
		ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RAWCONTENT,
				SchemaNames.EL_NSRAWCONTENT, dummyAttributes);
		ch.characters(renderedPage.toCharArray(), 0, renderedPage.length());
		ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RAWCONTENT,
				SchemaNames.EL_NSRAWCONTENT);
		ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
				SchemaNames.EL_NSERROR);

	}

	// SimpleCoverage.cover("Failed to parse ::\n" + renderedPage
	// + "\n:: from ::\n" + rwo.getContent());
	// Attributes dummyAttributes = new AttributesImpl();
	// ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
	// SchemaNames.EL_NSERROR, dummyAttributes);
	// ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
	// SchemaNames.EL_NSERRORDESC, dummyAttributes);
	// String s = "The Rendered Content did not parse correctly "
	// + ex.getMessage();
	// ch.characters(s.toCharArray(), 0, s.length());
	// ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
	// SchemaNames.EL_NSERRORDESC);
	// ch.startElement(SchemaNames.NS_CONTAINER,
	// SchemaNames.EL_RAWCONTENT, SchemaNames.EL_NSRAWCONTENT,
	// dummyAttributes);
	// ch.characters(renderedPage.toCharArray(), 0, renderedPage.length());
	// ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RAWCONTENT,
	// SchemaNames.EL_NSRAWCONTENT);
	// ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
	// SchemaNames.EL_NSERROR);

}
 
Example 6
Source File: XMLEscapeTransformer.java    From LoggerPlusPlus with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public String transform(String string) {
    return StringEscapeUtils.escapeXml11(string);
}
 
Example 7
Source File: XSLTEntityHandler.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
 * Serialises the rendered content of the RWiki Object to SAX
 * 
 * @param rwo
 * @param ch
 * @param withBreadCrumb 
 */
public void renderToXML(RWikiObject rwo, final ContentHandler ch, boolean withBreadCrumb, boolean escapeXML)
		throws SAXException, IOException
{

	String renderedPage;
	try
	{
		renderedPage = render(rwo,withBreadCrumb);
	}
	catch (Exception e)
	{
		renderedPage = Messages.getString("XSLTEntityHandler.32") + rwo.getName() + Messages.getString("XSLTEntityHandler.33") + e.getClass() + Messages.getString("XSLTEntityHandler.34") + e.getMessage(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		log.info(renderedPage, e);
	}
	String contentDigest = DigestHtml.digest(renderedPage);
	if (contentDigest.length() > 500)
	{
		contentDigest = contentDigest.substring(0, 500);
	}
	if (renderedPage == null || renderedPage.trim().length() == 0)
	{
		renderedPage = Messages.getString("XSLTEntityHandler.35"); //$NON-NLS-1$
	}
	if (contentDigest == null || contentDigest.trim().length() == 0)
	{
		contentDigest = Messages.getString("XSLTEntityHandler.36"); //$NON-NLS-1$
	}

	String cdataEscapedRendered = renderedPage
			.replaceAll("]]>", "]]>]]&gt;<![CDATA["); //$NON-NLS-1$ //$NON-NLS-2$
	String cdataContentDigest = contentDigest.replaceAll("]]>", "]]>]]&gt;<![CDATA["); //$NON-NLS-1$ //$NON-NLS-2$

       /* http://jira.sakaiproject.org/browse/SAK-13281
        * ensure all page content is escaped or double escaped before it goes into the parser,
        * if this is not done then the parser will unescape html entities during processing
        */		
       renderedPage = "<content><rendered>" + (escapeXML ? StringEscapeUtils.escapeXml11(renderedPage) : renderedPage) //$NON-NLS-1$
			+ "</rendered><rendered-cdata><![CDATA[" + cdataEscapedRendered + "]]></rendered-cdata><contentdigest><![CDATA[" + cdataContentDigest //$NON-NLS-1$ //$NON-NLS-2$
			+ "]]></contentdigest></content>"; //$NON-NLS-1$

	try
	{
		parseToSAX(renderedPage, ch);
	}
	catch (SAXException ex)
	{
		SimpleCoverage.cover("Failed to parse renderedPage from " + rwo.getName()); //$NON-NLS-1$
		Attributes dummyAttributes = new AttributesImpl();
		ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
				SchemaNames.EL_NSERROR, dummyAttributes);
		ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
				SchemaNames.EL_NSERRORDESC, dummyAttributes);
		String s = Messages.getString("XSLTEntityHandler.46") //$NON-NLS-1$
				+ ex.getMessage();
		ch.characters(s.toCharArray(), 0, s.length());
		ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
				SchemaNames.EL_NSERRORDESC);
		ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RAWCONTENT,
				SchemaNames.EL_NSRAWCONTENT, dummyAttributes);
		ch.characters(renderedPage.toCharArray(), 0, renderedPage.length());
		ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RAWCONTENT,
				SchemaNames.EL_NSRAWCONTENT);
		ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
				SchemaNames.EL_NSERROR);

	}

	// SimpleCoverage.cover("Failed to parse ::\n" + renderedPage
	// + "\n:: from ::\n" + rwo.getContent());
	// Attributes dummyAttributes = new AttributesImpl();
	// ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
	// SchemaNames.EL_NSERROR, dummyAttributes);
	// ch.startElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
	// SchemaNames.EL_NSERRORDESC, dummyAttributes);
	// String s = "The Rendered Content did not parse correctly "
	// + ex.getMessage();
	// ch.characters(s.toCharArray(), 0, s.length());
	// ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERRORDESC,
	// SchemaNames.EL_NSERRORDESC);
	// ch.startElement(SchemaNames.NS_CONTAINER,
	// SchemaNames.EL_RAWCONTENT, SchemaNames.EL_NSRAWCONTENT,
	// dummyAttributes);
	// ch.characters(renderedPage.toCharArray(), 0, renderedPage.length());
	// ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_RAWCONTENT,
	// SchemaNames.EL_NSRAWCONTENT);
	// ch.endElement(SchemaNames.NS_CONTAINER, SchemaNames.EL_ERROR,
	// SchemaNames.EL_NSERROR);

}
 
Example 8
Source File: FederationService.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@GET
public Response get(@Context UriInfo uriInfo,
                    @Context SecurityContext securityContext) {
    StringBuilder out = new StringBuilder(308)
        .append("<html>")
        .append("<head><title>WS Federation Spring Security Example</title></head>")
        .append("<body>")
        .append("<h1>Hello World</h1>")
        .append("Hello world<br>");

    out.append("Request url: ").append(uriInfo.getAbsolutePath()).append("<p>");

    out.append("<br><b>User</b><p>");
    Principal p = securityContext.getUserPrincipal();
    if (p != null) {
        out.append("Principal: ").append(p.getName()).append("<p>");
    }

    out.append("<br><b>Roles</b><p>");
    String[] roleListToCheck = new String[]{"Admin", "Manager", "User", "Authenticated"};
    for (String item: roleListToCheck) {
        out.append("Has role '").append(item).append("': ").append(
            (securityContext.isUserInRole(item)) ? "<b>yes</b>" : "no").append("<p>");
    }

    if (p instanceof FedizPrincipal) {
        FedizPrincipal fp = (FedizPrincipal)p;

        out.append("<br><b>Claims</b><p>");
        ClaimCollection claims = fp.getClaims();
        for (Claim c: claims) {
            out.append(c.getClaimType()).append(": ").append(c.getValue()).append("<p>");
        }
    } else {
        out.append("Principal is not instance of FedizPrincipal");
    }

    Element el = SecurityTokenThreadLocal.getToken();
    if (el != null) {
        out.append("<p>Bootstrap token...");
        try {
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transformer = transFactory.newTransformer();
            StringWriter buffer = new StringWriter();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.transform(new DOMSource(el), new StreamResult(buffer));
            String token = buffer.toString();
            String escapedXml = StringEscapeUtils.escapeXml11(token);
            out.append("<p>").append(escapedXml);
        } catch (Exception ex) {
            out.append("<p>Failed to transform cached element to string: ").append(ex.toString());
        }
    } else {
        out.append("<p>Bootstrap token not cached in thread local storage");
    }

    out.append("</body>");

    return Response.ok().type(MediaType.TEXT_HTML).entity(out.toString()).build();
}
 
Example 9
Source File: EncryptUtils.java    From platform with Apache License 2.0 4 votes vote down vote up
/**
 * Xml转码.
 */
public static String escapeXml(String xml) {
    return StringEscapeUtils.escapeXml11(xml);
}
 
Example 10
Source File: Utils.java    From Quelea with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Escape the XML special characters.
 * <p/>
 * @param s the string to escape.
 * @return the escaped string.
 */
public static String escapeXML(String s) {
	return StringEscapeUtils.escapeXml11(s);
}
 
Example 11
Source File: XmlUtility.java    From jstarcraft-core with Apache License 2.0 2 votes vote down vote up
/**
 * 对字符串执行XML1.1加密
 * 
 * @param string
 * @return
 */
public static final String escapeXml11(String string) {
    return StringEscapeUtils.escapeXml11(string);
}
 
Example 12
Source File: Encoder.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * XML-escapes the given String.
 * @param object the String.
 * @return an XML-escaped representation.
 */
public String xmlEncode( String object )
{
    return StringEscapeUtils.escapeXml11( object );
}