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

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

Introduction

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

Prototype

public static String escapeXml11(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:com.streamsets.pipeline.lib.el.StringEL.java

@ElFunction(prefix = "str", name = "escapeXML11", description = "Returns a string safe to embed in an XML 1.1 document.")
public static String escapeXml11(@ElParam("string") String string) {
    return StringEscapeUtils.escapeXml11(string);
}

From source file:com.esri.geoportal.commons.csw.client.impl.Client.java

/**
 * Creates fixed record./*from w  ww  .  j a  v a  2  s. c o m*/
 *
 * @param cswResponse response
 * @param recordId record id.
 * @return record data
 */
private String makeResourceFromCswResponse(String cswResponse, String recordId) {
    Pattern cswRecordStart = Pattern.compile("<csw:Record>");
    Pattern cswRecordEnd = Pattern.compile("</csw:Record>");

    Matcher cswRecordStartMatcher = cswRecordStart.matcher(cswResponse);
    Matcher cswRecordEndMatcher = cswRecordEnd.matcher(cswResponse);

    if (cswRecordStartMatcher.find() && cswRecordEndMatcher.find()) {
        String dcResponse = cswResponse.substring(cswRecordStartMatcher.end(), cswRecordEndMatcher.start());
        StringBuilder xml = new StringBuilder();
        xml.append(
                "<?xml version=\"1.0\"?><rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:ows=\"http://www.opengis.net/ows\" xmlns:dct=\"http://purl.org/dc/terms/\">");
        xml.append("<rdf:Description ");
        if (recordId.length() > 0) {
            xml.append("rdf:about=\"").append(StringEscapeUtils.escapeXml11(recordId)).append("\"");
        }
        xml.append(">");

        xml.append(dcResponse);

        xml.append("</rdf:Description>");
        xml.append("</rdf:RDF>");

        return xml.toString();
    }

    return cswResponse;
}

From source file:com.hygenics.parser.ManualReplacement.java

private void transform() {
    log.info("Transforming");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    for (String fpath : fpaths) {
        log.info("FILE: " + fpath);
        try {/*w  w w. ja  va  2s .  c o m*/
            // TRANSFORM
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(fpath));
            Node root = doc.getFirstChild();
            XPathFactory xfactory = XPathFactory.newInstance();
            XPath xpath = xfactory.newXPath();
            String database = null;
            String path = "//transformation/connection";

            log.info("Removing");
            for (String dbname : remove) {
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                if (conn != null) {
                    root.removeChild(conn);
                }
            }

            log.info("Transforming");
            for (String key : databaseAttributes.keySet()) {
                database = key;
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);

                if (conn != null) {
                    if (remove.contains(key)) {
                        root.removeChild(conn);
                    } else {
                        Map<String, String> attrs = databaseAttributes.get(database);
                        NodeList nl = conn.getChildNodes();
                        Set<String> keys = databaseAttributes.get(key).keySet();

                        for (int i = 0; i < nl.getLength(); i++) {
                            org.w3c.dom.Node n = nl.item(i);

                            if (keys.contains(n.getNodeName().trim())) {
                                n.setNodeValue(attrs.get(n.getNodeName()));
                            }
                        }
                    }
                }

                if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) {
                    log.info("Logging Manipulation");
                    log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null
                            ? "Removing Logging Data"
                            : "Adding Logging data");
                    String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table",
                            "step-log-table", "metrics-log-table" };
                    for (String section : sections) {
                        log.info("Changing Settings for " + section);
                        xepr = xpath.compile("//" + section + "/field/enabled");
                        NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET);
                        log.info("Nodes Found: " + Integer.toString(nodes.getLength()));
                        for (int i = 0; i < nodes.getLength(); i++) {
                            if (!this.log_to_table) {
                                nodes.item(i).setNodeValue("N");
                            } else {
                                nodes.item(i).setNodeValue("Y");
                            }
                        }

                        for (String nodeName : new String[] { "schema", "connection", "table",
                                "size_limit_lines", "interval", "timeout_days" }) {
                            if (!this.log_to_table) {
                                log.info("Changing Settings for Node: " + nodeName);
                                xepr = xpath.compile("//" + section + "/" + nodeName);
                                Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                                if (node != null) {
                                    if (!this.log_to_table) {
                                        node.setNodeValue(null);
                                    } else if (this.loggingTables.containsKey(section)
                                            && this.loggingTables.get(section).containsKey(nodeName)) {
                                        node.setNodeValue(this.loggingTables.get(section).get(nodeName));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // SET MAIN CONNECTION
            if (mainConnection != null) {
                XPathExpression xepr = xpath.compile(path);
                NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of
                // org.w3c it is
                // actually a NodeList
                for (int i = 0; i < conns.getLength(); i++) {
                    if (!conns.item(i).hasChildNodes()) {// only connection
                        // elements
                        // without child
                        // nodes have
                        // text content
                        conns.item(i).setNodeValue(mainConnection);
                    }
                }
            }

            if (this.replacements != null) {
                for (String key : this.replacements.keySet()) {
                    XPathExpression xepr = xpath.compile(key);
                    Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                    if (node != null) {
                        for (String attrVal : this.replacements.get(key).keySet()) {
                            log.info("Replacing Information at " + key + "at " + attrVal);
                            log.info("Replacement Will Be: "
                                    + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));

                            if (attrVal.toLowerCase().trim().equals("text")) {
                                node.setNodeValue(
                                        StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));
                                if (node.getNodeValue() == null) {
                                    node.setTextContent(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                }

                            } else {
                                NamedNodeMap nattrs = node.getAttributes();
                                Node n = nattrs.getNamedItem(attrVal);
                                if (n != null) {
                                    n.setNodeValue(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                } else {
                                    log.warn("Attribute Not Found " + attrVal);
                                }
                            }
                        }
                    } else {
                        log.warn("Node not found for " + key);
                    }
                }
            }

            // WRITE TO FILE
            log.info("Writing to File");
            TransformerFactory tfact = TransformerFactory.newInstance();
            Transformer transformer = tfact.newTransformer();
            DOMSource source = new DOMSource(doc);
            try (FileOutputStream stream = new FileOutputStream(new File(fpath))) {
                StreamResult result = new StreamResult(stream);
                transformer.transform(source, result);
                stream.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:ee.ria.xroad.common.message.SaxSoapParserImpl.java

@SneakyThrows
protected void writeStartElementXml(String prefix, QName element, Attributes attributes, Writer writer) {
    writer.append('<');
    String localName = element.getLocalPart();
    String tag = StringUtils.isEmpty(prefix) ? localName : prefix + ":" + localName;
    writer.append(tag);//  w w  w. ja v a2s. c om
    for (int i = 0; i < attributes.getLength(); i++) {
        String escapedAttrValue = StringEscapeUtils.escapeXml11(attributes.getValue(i));
        writer.append(String.format(" %s=\"%s\"", attributes.getQName(i), escapedAttrValue));
    }
    writer.append('>');
}

From source file:com.esri.geoportal.commons.csw.client.impl.Client.java

/**
 * Creates to internal xml request.//from   ww  w.  j a  v a 2 s  . c o  m
 *
 * @return string representing internal xml request
 */
private String createInternalXmlRequest(ICriteria criteria) {
    String request = "<?xml version='1.0' encoding='UTF-8' ?>";
    request += "<GetRecords>" + "<StartPosition>" + criteria.getStartPosition() + "</StartPosition>";
    request += "<MaxRecords>" + criteria.getMaxRecords() + "</MaxRecords>";
    request += "<KeyWord>"
            + (criteria.getSearchText() != null ? StringEscapeUtils.escapeXml11(criteria.getSearchText()) : "")
            + "</KeyWord>";
    request += ("<LiveDataMap>" + criteria.isLiveDataAndMapsOnly() + "</LiveDataMap>");
    if (criteria.getEnvelope() != null) {
        request += ("<Envelope>");
        request += "<MinX>" + criteria.getEnvelope().getXMin() + "</MinX>";
        request += "<MinY>" + criteria.getEnvelope().getYMin() + "</MinY>";
        request += "<MaxX>" + criteria.getEnvelope().getXMax() + "</MaxX>";
        request += "<MaxY>" + criteria.getEnvelope().getYMax() + "</MaxY>";
        request += "</Envelope>";
        request += "<RecordsFullyWithinEnvelope>" + (criteria.getOperation() == Contains)
                + "</RecordsFullyWithinEnvelope>";
        request += "<RecordsIntersectWithEnvelope>" + (criteria.getOperation() == Intersects)
                + "</RecordsIntersectWithEnvelope>";
    }
    if (criteria.getFromDate() != null) {
        request += "<FromDate>" + formatIsoDate(criteria.getFromDate()) + "</FromDate>";
    }
    if (criteria.getToDate() != null) {
        request += "<ToDate>" + formatIsoDate(criteria.getToDate()) + "</ToDate>";
    }
    request += "</GetRecords>";

    return request;
}

From source file:com.portfolio.data.utils.DomUtils.java

public static String getNodeAttributesString(Node node) {
    String ret = "";
    NamedNodeMap attributes = node.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Attr attribute = (Attr) attributes.item(i);
        ret += attribute.getName().trim() + "=\"" + StringEscapeUtils.escapeXml11(attribute.getValue().trim())
                + "\" ";
    }//from   w  w  w .j  a  v a  2 s .c om
    return ret;
}

From source file:org.ambraproject.wombat.util.ParseXmlUtil.java

private static void appendTextNode(StringBuilder nodeContent, Node child) {
    String text = child.getNodeValue();
    text = StringEscapeUtils.escapeXml11(text);
    nodeContent.append(text);/*from   ww w  .ja  v a 2  s.c  om*/
}

From source file:org.apache.nifi.util.FlowFilePackagerV1.java

private void writeAttributesEntry(final Map<String, String> attributes, final TarArchiveOutputStream tout)
        throws IOException {
    final StringBuilder sb = new StringBuilder();
    sb.append(/*from   www  . ja v  a 2s .  c  om*/
            "<?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();
}

From source file:org.ballerinalang.bre.bvm.BLangVM.java

private void execXMLOpcodes(StackFrame sf, int opcode, int[] operands) {
    int i;/*w  w w . ja v a 2 s. c o  m*/
    int j;
    int k;
    int localNameIndex;
    int uriIndex;
    int prefixIndex;

    BXML<?> xmlVal;
    BXMLQName xmlQName;

    switch (opcode) {
    case InstructionCodes.XMLATTRSTORE:
        i = operands[0];
        j = operands[1];
        k = operands[2];

        xmlVal = (BXML) sf.refRegs[i];
        if (xmlVal == null) {
            handleNullRefError();
            break;
        }

        xmlQName = (BXMLQName) sf.refRegs[j];
        if (xmlQName == null) {
            handleNullRefError();
            break;
        }

        xmlVal.setAttribute(xmlQName.getLocalName(), xmlQName.getUri(), xmlQName.getPrefix(), sf.stringRegs[k]);
        break;
    case InstructionCodes.XMLATTRLOAD:
        i = operands[0];
        j = operands[1];
        k = operands[2];

        xmlVal = (BXML) sf.refRegs[i];
        if (xmlVal == null) {
            handleNullRefError();
            break;
        }

        xmlQName = (BXMLQName) sf.refRegs[j];
        if (xmlQName == null) {
            handleNullRefError();
            break;
        }

        sf.stringRegs[k] = xmlVal.getAttribute(xmlQName.getLocalName(), xmlQName.getUri(),
                xmlQName.getPrefix());
        break;
    case InstructionCodes.XML2XMLATTRS:
        i = operands[0];
        j = operands[1];

        xmlVal = (BXML) sf.refRegs[i];
        if (xmlVal == null) {
            sf.refRegs[j] = null;
            break;
        }

        sf.refRegs[j] = new BXMLAttributes(xmlVal);
        break;
    case InstructionCodes.S2QNAME:
        i = operands[0];
        j = operands[1];
        k = operands[2];

        String qNameStr = sf.stringRegs[i];
        int parenEndIndex = qNameStr.indexOf('}');

        if (qNameStr.startsWith("{") && parenEndIndex > 0) {
            sf.stringRegs[j] = qNameStr.substring(parenEndIndex + 1, qNameStr.length());
            sf.stringRegs[k] = qNameStr.substring(1, parenEndIndex);
        } else {
            sf.stringRegs[j] = qNameStr;
            sf.stringRegs[k] = STRING_NULL_VALUE;
        }

        break;
    case InstructionCodes.NEWQNAME:
        localNameIndex = operands[0];
        uriIndex = operands[1];
        prefixIndex = operands[2];
        i = operands[3];

        String localname = sf.stringRegs[localNameIndex];
        localname = StringEscapeUtils.escapeXml11(localname);

        String prefix = sf.stringRegs[prefixIndex];
        prefix = StringEscapeUtils.escapeXml11(prefix);

        sf.refRegs[i] = new BXMLQName(localname, sf.stringRegs[uriIndex], prefix);
        break;
    case InstructionCodes.XMLLOAD:
        i = operands[0];
        j = operands[1];
        k = operands[2];

        xmlVal = (BXML) sf.refRegs[i];
        if (xmlVal == null) {
            handleNullRefError();
            break;
        }

        long index = sf.longRegs[j];
        sf.refRegs[k] = xmlVal.getItem(index);
        break;
    case InstructionCodes.NEWXMLELEMENT:
    case InstructionCodes.NEWXMLCOMMENT:
    case InstructionCodes.NEWXMLTEXT:
    case InstructionCodes.NEWXMLPI:
    case InstructionCodes.XMLSTORE:
        execXMLCreationOpcodes(sf, opcode, operands);
        break;
    default:
        throw new UnsupportedOperationException();
    }
}

From source file:org.ballerinalang.bre.bvm.BVM.java

private static void execXMLOpcodes(Strand ctx, StackFrame sf, int opcode, int[] operands) {
    int i;//from  w  w  w. j av a  2 s .  c  o  m
    int j;
    int k;
    int localNameIndex;
    int uriIndex;
    int prefixIndex;

    BXML<?> xmlVal;
    BXMLQName xmlQName;

    switch (opcode) {
    case InstructionCodes.XMLATTRSTORE:
        i = operands[0];
        j = operands[1];
        k = operands[2];

        xmlVal = Optional.of((BXML) sf.refRegs[i]).get();
        xmlQName = Optional.of((BXMLQName) sf.refRegs[j]).get();
        try {
            xmlVal.setAttribute(xmlQName.getLocalName(), xmlQName.getUri(), xmlQName.getPrefix(),
                    sf.stringRegs[k]);
        } catch (BallerinaException e) {
            ctx.setError(
                    BLangVMErrors.createError(ctx, BallerinaErrorReasons.XML_OPERATION_ERROR, e.getMessage()));
            handleError(ctx);
        }
        break;
    case InstructionCodes.XMLATTRLOAD:
        i = operands[0];
        j = operands[1];
        k = operands[2];

        xmlVal = Optional.of((BXML) sf.refRegs[i]).get();
        xmlQName = Optional.of((BXMLQName) sf.refRegs[j]).get();
        sf.stringRegs[k] = xmlVal.getAttribute(xmlQName.getLocalName(), xmlQName.getUri(),
                xmlQName.getPrefix());
        break;
    case InstructionCodes.XML2XMLATTRS:
        i = operands[0];
        j = operands[1];
        xmlVal = (BXML) sf.refRegs[i];
        sf.refRegs[j] = new BXMLAttributes(xmlVal);
        break;
    case InstructionCodes.S2QNAME:
        i = operands[0];
        j = operands[1];
        k = operands[2];

        String qNameStr = sf.stringRegs[i];
        int parenEndIndex = qNameStr.indexOf('}');

        if (qNameStr.startsWith("{") && parenEndIndex > 0) {
            sf.stringRegs[j] = qNameStr.substring(parenEndIndex + 1, qNameStr.length());
            sf.stringRegs[k] = qNameStr.substring(1, parenEndIndex);
        } else {
            sf.stringRegs[j] = qNameStr;
            sf.stringRegs[k] = STRING_NULL_VALUE;
        }

        break;
    case InstructionCodes.NEWQNAME:
        localNameIndex = operands[0];
        uriIndex = operands[1];
        prefixIndex = operands[2];
        i = operands[3];

        String localname = sf.stringRegs[localNameIndex];
        localname = StringEscapeUtils.escapeXml11(localname);

        String prefix = sf.stringRegs[prefixIndex];
        prefix = StringEscapeUtils.escapeXml11(prefix);

        sf.refRegs[i] = new BXMLQName(localname, sf.stringRegs[uriIndex], prefix);
        break;
    case InstructionCodes.XMLSEQLOAD:
        i = operands[0];
        j = operands[1];
        k = operands[2];

        xmlVal = Optional.of((BXML) sf.refRegs[i]).get();
        long index = sf.longRegs[j];
        try {
            sf.refRegs[k] = xmlVal.getItem(index);
        } catch (BallerinaException e) {
            ctx.setError(
                    BLangVMErrors.createError(ctx, BallerinaErrorReasons.XML_OPERATION_ERROR, e.getMessage()));
            handleError(ctx);
        }
        break;
    case InstructionCodes.XMLLOAD:
        i = operands[0];
        j = operands[1];
        k = operands[2];

        xmlVal = Optional.of((BXML) sf.refRegs[i]).get();
        String qname = sf.stringRegs[j];
        sf.refRegs[k] = xmlVal.children(qname);
        break;
    case InstructionCodes.XMLLOADALL:
        i = operands[0];
        j = operands[1];

        xmlVal = Optional.of((BXML) sf.refRegs[i]).get();
        sf.refRegs[j] = xmlVal.children();
        break;
    case InstructionCodes.NEWXMLELEMENT:
    case InstructionCodes.NEWXMLCOMMENT:
    case InstructionCodes.NEWXMLTEXT:
    case InstructionCodes.NEWXMLPI:
    case InstructionCodes.XMLSEQSTORE:
    case InstructionCodes.NEWXMLSEQ:
        execXMLCreationOpcodes(ctx, sf, opcode, operands);
        break;
    default:
        throw new UnsupportedOperationException();
    }
}