Example usage for org.apache.commons.lang3 StringEscapeUtils escapeXml

List of usage examples for org.apache.commons.lang3 StringEscapeUtils escapeXml

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringEscapeUtils escapeXml.

Prototype

@Deprecated
public static final String escapeXml(final String input) 

Source Link

Document

Escapes the characters in a String using XML entities.

For example: "bread" & "butter" => "bread" & "butter" .

Usage

From source file:ngmep.xml.XMLExporter.java

private static void exportWay(final Way way, final BufferedWriter writer, final boolean force)
        throws IOException {
    if (!way.isModified() && !force) {
        return;/*from w w w  .  j ava2s. c  om*/
    }
    for (Node node : way.getNodes()) {
        exportNode(node, writer, true);
    }
    final StringBuilder stringWay = new StringBuilder();
    stringWay.append("  ");
    stringWay.append("<way");
    stringWay.append(" id='").append(way.getId()).append("'");
    if (way.isModified()) {
        stringWay.append(" action='").append("modify").append("'");
    }
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
    stringWay.append(" timestamp='").append(sdf.format(new Date(way.getTimestamp()))).append("'");
    if (way.getUser() != null) {
        stringWay.append(" uid='").append(way.getUser().getId()).append("'");
        stringWay.append(" user='").append(StringEscapeUtils.escapeXml(way.getUser().getName())).append("'");
    }
    stringWay.append(" visible='true'");
    stringWay.append(" version='").append(way.getVersion()).append("'");
    stringWay.append(" changeset='").append(way.getChangeset()).append("'");
    if (way.getNodes().size() > 0 || way.getNumTags() > 0) {
        stringWay.append(">\n");
        for (Node node : way.getNodes()) {
            stringWay.append("    ");
            stringWay.append("<nd");
            stringWay.append(" ref='").append(node.getId()).append("'");
            stringWay.append(" />\n");
        }
        final Set<String> tags = way.getTagKeys();
        for (String key : tags) {
            stringWay.append("    ");
            stringWay.append("<tag");
            stringWay.append(" k='").append(StringEscapeUtils.escapeXml(key)).append("'");
            stringWay.append(" v='").append(StringEscapeUtils.escapeXml(way.getTag(key))).append("'");
            stringWay.append(" />\n");
        }
        stringWay.append("  </way>\n");
    } else {
        stringWay.append("/>\n");
    }
    writer.write(stringWay.toString());

}

From source file:ngmep.xml.XMLExporter.java

private static void exportNode(final Node node, final BufferedWriter writer, final boolean force)
        throws IOException {
    if (!node.isModified() && !force) {
        return;/*from w w w .ja  v  a2 s .  co  m*/
    }
    final StringBuilder nodeString = new StringBuilder();
    nodeString.append("  ");
    nodeString.append("<node");
    nodeString.append(" id='").append(node.getId()).append("'");
    if (node.isModified()) {
        nodeString.append(" action='").append("modify").append("'");
    }
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
    nodeString.append(" timestamp='").append(sdf.format(new Date(node.getTimestamp()))).append("'");
    if (node.getUser() != null) {
        nodeString.append(" uid='").append(node.getUser().getId()).append("'");
        nodeString.append(" user='").append(StringEscapeUtils.escapeXml(node.getUser().getName())).append("'");
    }
    nodeString.append(" visble='true'");
    nodeString.append(" version='").append(node.getVersion()).append("'");
    nodeString.append(" changeset='").append(node.getChangeset()).append("'");
    nodeString.append(" lat='").append(node.getLat()).append("'");
    nodeString.append(" lon='").append(node.getLon()).append("'");

    if (node.getNumTags() > 0) {
        nodeString.append(">\n");

        final Set<String> tags = node.getTagKeys();
        for (String key : tags) {
            nodeString.append("    ");
            nodeString.append("<tag");
            nodeString.append(" k='").append(StringEscapeUtils.escapeXml(key)).append("'");
            nodeString.append(" v='").append(StringEscapeUtils.escapeXml(node.getTag(key))).append("'");
            nodeString.append("/>\n");
        }
        nodeString.append("  </node>\n");

    } else {
        nodeString.append("/>\n");
    }

    writer.write(nodeString.toString());
}

From source file:nicta.com.au.patent.document.CreateUnifiedDocuments.java

public void writeUnifiedPatentDocument(PatentDocument pt, File directory)
        throws FileNotFoundException, UnsupportedEncodingException {
    String fileName = directory.getAbsolutePath() + "/" + pt.getUcid() + ".xml";
    total++;//from   w w w  .j av  a  2  s . c  o m
    System.out.println(total + "- Creating: " + fileName);
    try (PrintWriter writer = new PrintWriter(fileName, "ISO-8859-1")) {
        writer.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
        writer.println("<patent-document ucid=\"" + pt.getUcid() + "\">");
        writer.println("\t<bibliographic-data>");
        writer.println("\t\t<technical-data>");
        writer.println("\t\t\t<classifications-ipcr>");
        for (ClassificationIpcr ipc : pt.getTechnicalData().getClassificationIpcr()) {
            writer.println("\t\t\t\t<classification-ipcr>" + StringEscapeUtils.escapeXml(ipc.getContent())
                    + "</classification-ipcr>");
        }
        writer.println("\t\t\t</classifications-ipcr>");
        for (InventionTitle title : pt.getTechnicalData().getInventionTitle()) {
            writer.println("\t\t\t<invention-title  lang=\"" + title.getLang() + "\">"
                    + StringEscapeUtils.escapeXml(title.getContent()) + "</invention-title>");
        }
        writer.println("\t\t</technical-data>");

        writer.println("\t</bibliographic-data>");
        if (pt.getAbstrac() != null) {
            writer.println("\t<abstract lang=\"" + pt.getAbstrac().getLang() + "\">");
            writer.println(StringEscapeUtils.escapeXml(pt.getAbstrac().getContent()));
            writer.println("\t</abstract>");
        }
        if (pt.getDescription() != null) {
            writer.println("\t<description load-source=\"" + pt.getDescription().getLoadSource()
                    + "\" status=\"" + pt.getDescription().getStatus() + "\" lang=\""
                    + pt.getDescription().getLang() + "\">");

            for (P p : pt.getDescription().getP()) {
                writer.println("\t\t<p num=\"" + p.getNum() + "\">");
                writer.println(StringEscapeUtils.escapeXml(p.getContent()));
                writer.println("\t\t</p>");
            }
            writer.println("\t</description>");
        }
        if (pt.getClaims() != null) {
            for (Claims claims : pt.getClaims()) {
                writer.println("\t<claims load-source=\"" + claims.getLoadSource() + "\" status=\""
                        + claims.getStatus() + "\" lang=\"" + claims.getLang() + "\">");
                for (Claim claim : claims.getClaim()) {
                    writer.println("\t\t<claim num=\"" + claim.getNum() + "\">");
                    writer.println(StringEscapeUtils.escapeXml(claim.getClaimText()));
                    writer.println("\t\t</claim>");
                }
                writer.println("\t</claims>");
            }
        }
        writer.println("</patent-document>");
        writer.flush();
    }
}

From source file:org.apache.cxf.fediz.example.FederationService.java

@GET
public Response get(@Context UriInfo uriInfo, @Context SecurityContext securityContext) {

    ResponseBuilder rb = Response.ok().type("text/html");

    StringBuilder out = new StringBuilder();
    out.append("<html>");
    out.append("<head><title>WS Federation Spring Security Example</title></head>");
    out.append("<body>");
    out.append("<h1>Hello World</h1>");
    out.append("Hello world<br>");
    out.append("Request url: " + uriInfo.getAbsolutePath().toString() + "<p>");

    out.append("<br><b>User</b><p>");
    Principal p = securityContext.getUserPrincipal();
    if (p != null) {
        out.append("Principal: " + p.getName() + "<p>");
    }/*from  w w w .  j  a va 2 s. c  o m*/

    // Access Spring security context
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof FederationAuthenticationToken) {
        out.append("Roles of user:<p><ul>");
        FederationAuthenticationToken fedAuthToken = (FederationAuthenticationToken) auth;
        for (GrantedAuthority item : fedAuthToken.getAuthorities()) {
            out.append("<li>" + item.getAuthority() + "</li>");
        }
        out.append("</ul>");

        if (fedAuthToken.getUserDetails() instanceof FederationUser) {
            out.append("<br><b>Claims</b><p>");
            ClaimCollection claims = ((FederationUser) fedAuthToken.getUserDetails()).getClaims();
            for (Claim c : claims) {
                out.append(c.getClaimType().toString() + ": " + c.getValue() + "<p>");
            }
        } else {
            out.append("FederationAuthenticationToken found but not FederationUser");
        }

    } else {
        out.append("No FederationAuthenticationToken found in Spring Security Context.");
    }

    Element el = SecurityTokenThreadLocal.getToken();
    if (el != null) {
        out.append("<p>Bootstrap token...");
        String token = null;
        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));
            token = buffer.toString();
            @SuppressWarnings("deprecation")
            String escapedXml = StringEscapeUtils.escapeXml(token);
            out.append("<p>" + escapedXml);
        } catch (Exception ex) {
            out.append("<p>Failed to transform cached element to string: " + ex.toString());
        }
    } else {
        out.append("<p>Bootstrap token not cached in thread local storage");
    }

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

    return rb.entity(out.toString()).build();
}

From source file:org.apache.cxf.fediz.example.FederationServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head><title>WS Federation Tomcat Examples</title></head>");
    out.println("<body>");
    out.println("<h1>Hello World</h1>");
    out.println("Hello world<br>");
    out.println("Request url: " + request.getRequestURL().toString() + "<p>");

    out.println("<br><b>User</b><p>");
    Principal p = request.getUserPrincipal();
    if (p != null) {
        out.println("Principal: " + p.getName() + "<p>");
    }// w w w . j a  v  a 2s . c  om

    out.println("<br><b>Roles</b><p>");
    List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated");
    for (String item : roleListToCheck) {
        out.println("Has role '" + item + "': " + ((request.isUserInRole(item)) ? "<b>yes</b>" : "no") + "<p>");
    }

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

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

    Element el = SecurityTokenThreadLocal.getToken();
    if (el != null) {
        out.println("<p>Bootstrap token...");
        String token = null;
        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));
            token = buffer.toString();
            out.println("<p>" + StringEscapeUtils.escapeXml(token));
        } catch (Exception ex) {
            out.println("<p>Failed to transform cached element to string: " + ex.toString());
        }
    } else {
        out.println("<p>Bootstrap token not cached in thread local storage");
    }

    out.println("</body>");
}

From source file:org.apache.cxf.fediz.service.idp.beans.STSClientAction.java

/**
 * @param context//  ww  w  .jav a  2s  .  c  om
 *            the webflow request context
 * @return a serialized RP security token
 * @throws Exception
 */
public String submit(RequestContext context) throws Exception {

    String wtrealm = (String) WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_TREALM);

    SecurityToken idpToken = getSecurityToken(context);

    Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, IDP_CONFIG);

    Bus cxfBus = getBus();

    IdpSTSClient sts = new IdpSTSClient(cxfBus);
    sts.setAddressingNamespace(HTTP_WWW_W3_ORG_2005_08_ADDRESSING);

    Application serviceConfig = idpConfig.findApplication(wtrealm);
    if (serviceConfig == null) {
        LOG.warn("No service config found for " + wtrealm);
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }

    // Parse wreq parameter - we only support parsing TokenType and KeyType for now
    String wreq = (String) WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_REQUEST);
    String stsTokenType = null;
    String stsKeyType = keyType;
    if (wreq != null) {
        try {
            Document wreqDoc = DOMUtils.readXml(new StringReader(wreq));
            Element wreqElement = wreqDoc.getDocumentElement();
            if (wreqElement != null && "RequestSecurityToken".equals(wreqElement.getLocalName())
                    && (STSUtils.WST_NS_05_12.equals(wreqElement.getNamespaceURI())
                            || HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST
                                    .equals(wreqElement.getNamespaceURI()))) {
                Element tokenTypeElement = DOMUtils.getFirstChildWithName(wreqElement,
                        wreqElement.getNamespaceURI(), "TokenType");
                if (tokenTypeElement != null) {
                    stsTokenType = tokenTypeElement.getTextContent();
                }
                Element keyTypeElement = DOMUtils.getFirstChildWithName(wreqElement,
                        wreqElement.getNamespaceURI(), "KeyType");
                if (keyTypeElement != null) {
                    stsKeyType = keyTypeElement.getTextContent();
                }
            }
        } catch (Exception e) {
            LOG.warn("Error parsing 'wreq' parameter: " + e.getMessage());
            throw new ProcessingException(TYPE.BAD_REQUEST);
        }
    }

    if (stsTokenType != null) {
        sts.setTokenType(stsTokenType);
    } else if (serviceConfig.getTokenType() != null && serviceConfig.getTokenType().length() > 0) {
        sts.setTokenType(serviceConfig.getTokenType());
    } else {
        sts.setTokenType(getTokenType());
    }

    if (serviceConfig.getPolicyNamespace() != null && serviceConfig.getPolicyNamespace().length() > 0) {
        sts.setWspNamespace(serviceConfig.getPolicyNamespace());
    }

    LOG.debug("TokenType {} set for realm {}", sts.getTokenType(), wtrealm);

    sts.setKeyType(stsKeyType);
    if (HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_PUBLICKEY.equals(stsKeyType)) {
        HttpServletRequest servletRequest = WebUtils.getHttpServletRequest(context);
        if (servletRequest != null) {
            X509Certificate certs[] = (X509Certificate[]) servletRequest
                    .getAttribute("javax.servlet.request.X509Certificate");
            if (certs != null && certs.length > 0) {
                sts.setUseCertificateForConfirmationKeyInfo(true);
                sts.setUseKeyCertificate(certs[0]);
            } else {
                LOG.info("Can't send a PublicKey KeyType as no client certs are available");
                sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
            }
        }
    }

    processWsdlLocation(context);
    sts.setWsdlLocation(wsdlLocation);
    sts.setServiceQName(new QName(namespace, wsdlService));
    sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
    if (use200502Namespace) {
        sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
    }

    if (serviceConfig.getRequestedClaims() != null && serviceConfig.getRequestedClaims().size() > 0) {
        addClaims(sts, serviceConfig.getRequestedClaims());
        LOG.debug("Requested claims set for {}", wtrealm);
    }

    sts.setEnableLifetime(true);
    if (serviceConfig.getLifeTime() > 0) {
        try {
            int lifetime = serviceConfig.getLifeTime();
            sts.setTtl(lifetime);
            sts.setEnableLifetime(lifetime > 0);
            LOG.debug("Lifetime set to {} seconds for realm {}", serviceConfig.getLifeTime(), wtrealm);
        } catch (NumberFormatException ex) {
            LOG.warn("Invalid lifetime configured for service provider " + wtrealm);
            sts.setTtl(this.ttl);
            sts.setEnableLifetime(this.ttl > 0);
        }
    } else {
        sts.setTtl(this.ttl);
        sts.setEnableLifetime(this.ttl > 0);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Lifetime set to {} seconds for realm {}", this.ttl, wtrealm);
        }
    }

    sts.setOnBehalfOf(idpToken.getToken());
    if (!(serviceConfig.getProtocol() == null
            || FederationConstants.WS_FEDERATION_NS.equals(serviceConfig.getProtocol()))) {
        LOG.error("Protocol {} not supported for realm {} ", serviceConfig.getProtocol(), wtrealm);
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }

    String rpToken = sts.requestSecurityTokenResponse(wtrealm);

    InputStream is = new ByteArrayInputStream(rpToken.getBytes());
    Document doc = StaxUtils.read(is);
    NodeList nd = doc.getElementsByTagName("saml2:Assertion");
    if (nd.getLength() == 0) {
        nd = doc.getElementsByTagName("saml1:Assertion");
    }
    Element e = (Element) nd.item(0);
    SamlAssertionWrapper aw = new SamlAssertionWrapper(e);
    String id = aw.getId();

    LOG.info("[RP_TOKEN={}] successfully created for realm [{}] on behalf of [IDP_TOKEN={}]", id, wtrealm,
            idpToken.getId());
    return StringEscapeUtils.escapeXml(rpToken);
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java

private void processCharacters(Characters event) throws XPathExpressionException {
    //System.out.println( "T[" + event.isCData() + "," + event.isWhiteSpace() + "," + event.isIgnorableWhiteSpace() + "]=" + event );
    Level level = stack.peek();/*from ww  w  .jav  a  2  s. com*/
    Node node = stack.peek().node;
    if (event.isCData()) {
        node.appendChild(document.createCDATASection(event.getData()));
    } else {
        node.appendChild(document.createTextNode(event.getData()));
    }
    if (!currentlyBuffering()) {
        String value = event.getData();
        if (!event.isWhiteSpace()) {
            if (level.scopeConfig == null || level.scopeConfig.getSelectors().isEmpty()) {
                value = filterText(extractQName(node), value, null);
            } else {
                UrlRewriteFilterPathDescriptor path = pickFirstMatchingPath(level);
                if (path instanceof UrlRewriteFilterApplyDescriptor) {
                    String rule = ((UrlRewriteFilterApplyDescriptor) path).rule();
                    value = filterText(extractQName(node), value, rule);
                }
            }
        }
        if (event.isCData()) {
            writer.write("<![CDATA[");
            writer.write(value);
            writer.write("]]>");
        } else {
            writer.write(StringEscapeUtils.escapeXml(value));
        }
    }
}

From source file:org.apache.struts2.components.Property.java

private String prepare(String value) {
    String result = value;//w w w  .ja  v  a 2 s  .c o m
    if (escapeHtml) {
        result = StringEscapeUtils.escapeHtml4(result);
    }
    if (escapeJavaScript) {
        result = StringEscapeUtils.escapeEcmaScript(result);
    }
    if (escapeXml) {
        result = StringEscapeUtils.escapeXml(result);
    }
    if (escapeCsv) {
        result = StringEscapeUtils.escapeCsv(result);
    }

    return result;
}

From source file:org.auraframework.system.AuraSystemUITest.java

@SuppressWarnings("unchecked")
private void checkDef(String descriptorString, Class<? extends Definition> defClass, Mode mode)
        throws Exception {
    Aura.getContextService().endContext();
    AuraContext context = Aura.getContextService().startContext(mode, Format.HTML,
            Authentication.AUTHENTICATED);

    try {/*from www. java2s  .  c  o m*/
        LOG.println("^*************************************************************************************");
        LOG.println(DefType.getDefType(defClass) + " - " + mode + " - " + descriptorString);
        DefDescriptor<? extends Definition> desc = Aura.getDefinitionService()
                .getDefDescriptor(descriptorString, defClass);

        // check source
        Source<?> source = context.getDefRegistry().getSource(desc);
        if (source == null) {
            LOG.println("SOURCE NOT FOUND!");
        } else if (source instanceof StringSource) {
            LOG.println("from StringSource");
        } else {
            String url = source.getUrl();
            URL sourceUrl = new URL(url);
            String sourcePath = sourceUrl.getPath();
            LOG.println("source url: " + sourceUrl);
            LOG.println("source path: " + sourcePath);
            LOG.println("canRead path: " + new File(sourcePath).canRead());
        }

        // check compile
        Definition def = null;
        try {
            def = Aura.getDefinitionService().getDefinition(desc);
            LOG.println("def isValid: " + def.isValid());
            LOG.println("uid: " + context.getDefRegistry().getUid(null, desc));
        } catch (Throwable t) {
            LOG.println("ERROR GETTING DEF:");
            t.printStackTrace(LOG);
        }

        if (source != null) {
            LOG.println("contents:");
            LOG.println(StringEscapeUtils.escapeXml(source.getContents()));
        }

        if (def != null && def instanceof BaseComponentDef) {
            // get app js
            checkResource((DefDescriptor<? extends BaseComponentDef>) desc, mode, Format.JS, "app.js");
            LOG.println();

            // get app css
            checkResource((DefDescriptor<? extends BaseComponentDef>) desc, mode, Format.CSS, "app.css");
            LOG.println();
        }
    } finally {
        Aura.getContextService().endContext();
        LOG.println();
    }
}

From source file:org.brunocvcunha.taskerbox.core.TaskerboxXmlReader.java

private void handleConcreteChannelNode(Element xmlChannel) throws Exception {
    log.info("Found channel: " + xmlChannel.getName() + ": " + xmlChannel.toString());

    StringWriter sw = new StringWriter();
    XMLWriter writer = new XMLWriter(sw);
    writer.write(xmlChannel);/*w ww  .ja v a  2  s.co  m*/

    String macroElement = sw.toString();

    for (String defaultAttr : this.tasker.getDefaultProperties().keySet()) {
        macroElement = macroElement.replace("{" + defaultAttr + "}",
                this.tasker.getDefaultProperties().get(defaultAttr));
    }
    for (String defaultAttr : this.tasker.getDefaultProperties().keySet()) {
        macroElement = macroElement.replace("default-" + defaultAttr + "=\"\"", defaultAttr + "=\""
                + StringEscapeUtils.escapeXml(this.tasker.getDefaultProperties().get(defaultAttr)) + "\"");
    }

    log.debug("Creating channel: " + macroElement);
    Element replacedXmlChannel = new SAXReader().read(new StringReader(macroElement)).getRootElement();

    TaskerboxChannel<?> channel = TaskerboxFactory.buildChannel(replacedXmlChannel);
    TaskerboxLauncher.startChannel(channel, this.tasker.getFrame(), this.tasker.getDaemons(),
            this.tasker.getChannels());

}