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:architecture.common.xml.XmlProperties.java

/**
 * Sets a property to an array of values. Multiple values matching the same
 * property is mapped to an XML file as multiple elements containing each
 * value. For example, using the name "foo.bar.prop", and the value string
 * array containing {"some value", "other value", "last value"} would
 * produce the following XML:/*from   w  w  w. ja va 2s  .  c  o  m*/
 * 
 * <pre>
 * &lt;foo&gt;
 *     &lt;bar&gt;
 *         &lt;prop&gt;some value&lt;/prop&gt;
 *         &lt;prop&gt;other value&lt;/prop&gt;
 *         &lt;prop&gt;last value&lt;/prop&gt;
 *     &lt;/bar&gt;
 * &lt;/foo&gt;
 * </pre>
 *
 * @param name
 *            the name of the property.
 * @param values
 *            the values for the property (can be empty but not null).
 */
public void setProperties(String name, List<String> values) {
    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy,
    // stopping one short.
    Element element = document.getRootElement();
    for (int i = 0; i < propName.length - 1; i++) {
        // If we don't find this part of the property in the XML heirarchy
        // we add it as a new node
        if (element.element(propName[i]) == null) {
            element.addElement(propName[i]);
        }
        element = element.element(propName[i]);
    }
    String childName = propName[propName.length - 1];
    // We found matching property, clear all children.
    List<Element> toRemove = new ArrayList<Element>();
    Iterator iter = element.elementIterator(childName);
    while (iter.hasNext()) {
        toRemove.add((Element) iter.next());
    }
    for (iter = toRemove.iterator(); iter.hasNext();) {
        element.remove((Element) iter.next());
    }
    // Add the new children.
    for (String value : values) {
        Element childElement = element.addElement(childName);
        if (value.startsWith("<![CDATA[")) {
            Iterator it = childElement.nodeIterator();
            while (it.hasNext()) {
                Node node = (Node) it.next();
                if (node instanceof CDATA) {
                    childElement.remove(node);
                    break;
                }
            }
            childElement.addCDATA(value.substring(9, value.length() - 3));
        } else {
            childElement.setText(StringEscapeUtils.escapeXml(value));
        }
    }
    saveProperties();

    // Generate event.
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("value", values);

    // PropertyEventDispatcher.dispatchEvent(name,
    // PropertyEventDispatcher.EventType.xml_property_set, params);

}

From source file:com.suneee.core.util.XMLProperties.java

/**
 * Sets a property to an array of values. Multiple values matching the same property
 * is mapped to an XML file as multiple elements containing each value.
 * For example, using the name "foo.bar.prop", and the value string array containing
 * {"some value", "other value", "last value"} would produce the following XML:
 * <pre>//w w  w  .ja v a 2 s.c  o  m
 * &lt;foo&gt;
 *     &lt;bar&gt;
 *         &lt;prop&gt;some value&lt;/prop&gt;
 *         &lt;prop&gt;other value&lt;/prop&gt;
 *         &lt;prop&gt;last value&lt;/prop&gt;
 *     &lt;/bar&gt;
 * &lt;/foo&gt;
 * </pre>
 *
 * @param name the name of the property.
 * @param values the values for the property (can be empty but not null).
 */
public void setProperties(String name, List<String> values) {
    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy,
    // stopping one short.
    Element element = document.getRootElement();
    for (int i = 0; i < propName.length - 1; i++) {
        // If we don't find this part of the property in the XML heirarchy
        // we add it as a new node
        if (element.element(propName[i]) == null) {
            element.addElement(propName[i]);
        }
        element = element.element(propName[i]);
    }
    String childName = propName[propName.length - 1];
    // We found matching property, clear all children.
    List<Element> toRemove = new ArrayList<Element>();
    Iterator iter = element.elementIterator(childName);
    while (iter.hasNext()) {
        toRemove.add((Element) iter.next());
    }
    for (iter = toRemove.iterator(); iter.hasNext();) {
        element.remove((Element) iter.next());
    }
    // Add the new children.
    for (String value : values) {
        Element childElement = element.addElement(childName);
        if (value.startsWith("<![CDATA[")) {
            Iterator it = childElement.nodeIterator();
            while (it.hasNext()) {
                Node node = (Node) it.next();
                if (node instanceof CDATA) {
                    childElement.remove(node);
                    break;
                }
            }
            childElement.addCDATA(value.substring(9, value.length() - 3));
        } else {
            childElement.setText(StringEscapeUtils.escapeXml(value));
        }
    }
    saveProperties();

    // Generate event.
    /*Map<String, Object> params = new HashMap<String, Object>();
    params.put("value", values);
    PropertyEventDispatcher.dispatchEvent(name,
        PropertyEventDispatcher.EventType.xml_property_set, params);*/
}

From source file:architecture.common.xml.XmlProperties.java

/**
 * Sets the value of the specified property. If the property doesn't
 * currently exist, it will be automatically created.
 *
 * @param name//w w  w .j  ava2  s . co m
 *            the name of the property to set.
 * @param value
 *            the new value for the property.
 */
public synchronized void setProperty(String name, String value) {
    if (!StringEscapeUtils.escapeXml(name).equals(name)) {
        throw new IllegalArgumentException(L10NUtils.getMessage("002155"));
    }
    if (name == null) {
        return;
    }
    if (value == null) {
        value = "";
    }

    // Set cache correctly with prop name and value.
    propertyCache.put(name, value);

    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy.
    Element element = document.getRootElement();
    for (String aPropName : propName) {
        // If we don't find this part of the property in the XML heirarchy
        // we add it as a new node
        if (element.element(aPropName) == null) {
            element.addElement(aPropName);
        }
        element = element.element(aPropName);
    }
    // Set the value of the property in this node.
    if (value.startsWith("<![CDATA[")) {
        Iterator it = element.nodeIterator();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node instanceof CDATA) {
                element.remove(node);
                break;
            }
        }
        element.addCDATA(value.substring(9, value.length() - 3));
    } else {
        element.setText(value);
    }
    // Write the XML properties to disk
    saveProperties();

    // Generate event.
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("value", value);

    // PropertyEventDispatcher.dispatchEvent(name,
    // PropertyEventDispatcher.EventType.xml_property_set, params);
}

From source file:eu.musesproject.server.contextdatareceiver.JSONManager.java

public static JSONObject createConfigUpdateJSON(String requestType, MusesConfig config,
        List<SensorConfiguration> sensorConfig, ConnectionConfig connConfig) {
    JSONObject root = new JSONObject();
    try {/*  w ww . j  a  v  a2 s .  c  o m*/

        root.put(JSONIdentifiers.REQUEST_TYPE_IDENTIFIER, requestType);
        String configXML = "";
        configXML += xmlProperty(JSONIdentifiers.SILENT_MODE, String.valueOf(config.getSilentMode()));
        if (config.getConfigName() != null) {
            configXML += xmlProperty(JSONIdentifiers.CONFIG_NAME, config.getConfigName());
        }
        root.put(JSONIdentifiers.MUSES_CONFIG, XML.toJSONObject(configXML));

        //Sensor configuration
        String sensorConfigXML = "";
        for (Iterator iterator = sensorConfig.iterator(); iterator.hasNext();) {
            SensorConfiguration sensorConfiguration = (SensorConfiguration) iterator.next();
            sensorConfigXML += "<" + JSONIdentifiers.SENSOR_PROPERTY + ">";
            sensorConfigXML += xmlProperty(JSONIdentifiers.SENSOR_TYPE,
                    StringEscapeUtils.escapeXml(String.valueOf(sensorConfiguration.getSensorType())));
            sensorConfigXML += xmlProperty(JSONIdentifiers.KEY,
                    StringEscapeUtils.escapeXml(String.valueOf(sensorConfiguration.getKeyProperty())));
            sensorConfigXML += xmlProperty(JSONIdentifiers.VALUE,
                    StringEscapeUtils.escapeXml(String.valueOf(sensorConfiguration.getValueProperty())));
            sensorConfigXML += "</" + JSONIdentifiers.SENSOR_PROPERTY + ">";
        }

        root.put(JSONIdentifiers.SENSOR_CONFIGURATION, XML.toJSONObject(sensorConfigXML));

        //Connection configuration
        String connConfigXML = "";
        connConfigXML += xmlProperty(JSONIdentifiers.TIMEOUT, connConfig.getTimeout());
        connConfigXML += xmlProperty(JSONIdentifiers.POLL_TIMEOUT, connConfig.getPollTimeout());
        connConfigXML += xmlProperty(JSONIdentifiers.SLEEP_POLL_TIMEOUT, connConfig.getSleepPollTimeout());
        connConfigXML += xmlProperty(JSONIdentifiers.POLLING_ENABLED, connConfig.getPollingEnabled());
        connConfigXML += xmlProperty(JSONIdentifiers.LOGIN_ATTEMPTS, connConfig.getLoginAttempts());

        root.put(JSONIdentifiers.CONNECTION_CONFIG, XML.toJSONObject(connConfigXML));

    } catch (JSONException e) {
        e.printStackTrace();
    }

    return root;
}

From source file:com.suneee.core.util.XMLProperties.java

/**
 * Sets the value of the specified property. If the property doesn't
 * currently exist, it will be automatically created.
 *
 * @param name  the name of the property to set.
 * @param value the new value for the property.
 *//*  ww w .jav  a2 s .c  o  m*/
public synchronized void setProperty(String name, String value) {
    if (!StringEscapeUtils.escapeXml(name).equals(name)) {
        throw new IllegalArgumentException("Property name cannot contain XML entities.");
    }
    if (name == null) {
        return;
    }
    if (value == null) {
        value = "";
    }

    // Set cache correctly with prop name and value.
    propertyCache.put(name, value);

    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML heirarchy.
    Element element = document.getRootElement();
    for (String aPropName : propName) {
        // If we don't find this part of the property in the XML heirarchy
        // we add it as a new node
        if (element.element(aPropName) == null) {
            element.addElement(aPropName);
        }
        element = element.element(aPropName);
    }
    // Set the value of the property in this node.
    if (value.startsWith("<![CDATA[")) {
        Iterator it = element.nodeIterator();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node instanceof CDATA) {
                element.remove(node);
                break;
            }
        }
        element.addCDATA(value.substring(9, value.length() - 3));
    } else {
        element.setText(value);
    }
    // Write the XML properties to disk
    saveProperties();

    // Generate event.
    /*   Map<String, Object> params = new HashMap<String, Object>();
       params.put("value", value);
       PropertyEventDispatcher.dispatchEvent(name,
        PropertyEventDispatcher.EventType.xml_property_set, params);*/
}

From source file:hadoop.UIUCWikifierAppHadoop.java

public static String getWikifierOutput(LinkingProblem problem) {
    StringBuilder res = new StringBuilder();

    for (Mention entity : problem.components) {
        if (entity.topCandidate == null)
            continue;
        String escapedSurface = StringEscapeUtils.escapeXml(entity.surfaceForm.replace('\n', ' '));
        res.append(escapedSurface);//from  w  ww .ja  v  a 2s.  c om
        res.append(" ");
        res.append(entity.charStart);
        res.append(":");
        res.append(entity.charStart + entity.charLength);
        res.append(" ");
        res.append(entity.topCandidate.titleName);
        res.append(" ");
        res.append(entity.linkerScore);
        res.append("\t");
    }
    return res.toString().trim();
}

From source file:com.rockagen.commons.util.CommUtil.java

/**
 * escape XML see StringEscapeUtils.escapeXml(str)
 *
 * @param str value/*from  w ww.jav a  2s  .c om*/
 * @return string
 */
public static String escapeXml(String str) {
    if (isBlank(str)) {
        return str;
    }
    return StringEscapeUtils.escapeXml(str);

}

From source file:net.frogmouth.ddf.nitfinputtransformer.NitfInputTransformer.java

private String buildMetadataEntry(String label, String value) {
    StringBuilder entryBuilder = new StringBuilder();
    entryBuilder.append("    <");
    entryBuilder.append(label);// w w  w .j a va 2 s .  c  o  m
    entryBuilder.append(">");
    entryBuilder.append(StringEscapeUtils.escapeXml(value));
    entryBuilder.append("</");
    entryBuilder.append(label);
    entryBuilder.append(">\n");
    return entryBuilder.toString();
}

From source file:edu.virginia.iath.snac.helpers.GeoNamesHelper.java

/**
 * Cleans a string of extraneous characters, to create a normal form.  Removes parentheses and brackets.  
 * Replaces periods (.) with spaces if the periodToSpace parameter is true, else it removes periods.
 * //from   w  w w . ja  va 2s .co  m
 * @param string String to clean.
 * @param periodToSpace If true, replaces periods with spaces. If false, removes periods.
 * @return Cleaned string.
 */
public String cleanString(String string, boolean periodToSpace) {
    String result = StringEscapeUtils.escapeXml(string);
    //Normalize the string
    if (periodToSpace)
        result = result.toLowerCase().replaceAll("\\.", " ");

    result = result.toLowerCase().replaceAll("\\.", "");

    // If the string starts with a parenthesis, then we don't want to consider that as part of a
    // clarification string, so we'll remove it first
    if (result.startsWith("(")) {
        result = result.substring(1);
    }

    // Convert (place) to , place
    // for now, not using the regex, but replacing the ( with , and ) with nothing
    if (result.contains("(") && result.contains(")")) {
        result = result.replace("(", ", ");
        result = result.replace(")", "");
    }

    // Clean up the string
    result = result.replace("(", "");
    result = result.replace(")", "");
    result = result.replace("]", "");
    result = result.replace("[", "");
    result = result.replace(":", "");

    // Remove possessives:
    result = result.replace("'s", "");
    result = result.replace("'s", "");

    result = result.replace("&quot;", "");
    result = result.replace("&apos;s", "");

    // Trim the string
    result = result.trim();

    return result;
}

From source file:ngmep.xml.XMLExporter.java

private static void exportRelation(final Relation relation, final BufferedWriter writer, final boolean force)
        throws IOException {
    if (!relation.isModified() && !force) {
        return;/*from w w w  . j  av  a2s  .c om*/
    }
    for (RelationMember member : relation.getMembers()) {
        internalExport(member.getEntity(), writer, true);
    }
    final StringBuilder stringRelation = new StringBuilder();
    stringRelation.append("<relation");
    stringRelation.append(" id='").append(relation.getId()).append("'");
    if (relation.isModified()) {
        stringRelation.append(" action='").append("modify").append("'");
    }
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
    stringRelation.append(" timestamp='").append(sdf.format(new Date(relation.getTimestamp()))).append("'");
    if (relation.getUser() != null) {
        stringRelation.append(" uid='").append(relation.getUser().getId()).append("'");
        stringRelation.append(" user='").append(StringEscapeUtils.escapeXml(relation.getUser().getName()))
                .append("'");
    }
    stringRelation.append(" visible='true'");
    stringRelation.append(" version='").append(relation.getVersion()).append("'");
    stringRelation.append(" changeset='").append(relation.getChangeset()).append("'");
    if (relation.getMembers().size() > 0 || relation.getNumTags() > 0) {
        stringRelation.append(">\n");

        for (RelationMember member : relation.getMembers()) {
            String tipo = "node";
            if (member.getEntity() instanceof Node) {
                tipo = "node";
            } else if (member.getEntity() instanceof Way) {
                tipo = "way";
            }
            stringRelation.append("    ");
            stringRelation.append("<member type='").append(tipo).append("'");
            stringRelation.append(" ref='").append(member.getEntity().getId()).append("'");
            stringRelation.append(" role='").append(StringEscapeUtils.escapeXml(member.getRole())).append("'");
            stringRelation.append(" />\n");
        }
        final Set<String> tags = relation.getTagKeys();
        for (String key : tags) {
            stringRelation.append("    ");
            stringRelation.append("<tag");
            stringRelation.append(" k='").append(StringEscapeUtils.escapeXml(key)).append("'");
            stringRelation.append(" v='").append(StringEscapeUtils.escapeXml(relation.getTag(key))).append("'");
            stringRelation.append(" />\n");
        }
        stringRelation.append("</relation>\n");
    } else {
        stringRelation.append("/>\n");
    }
    writer.write(stringRelation.toString());
    /*
     <osm version="0.6" generator="OpenStreetMap server">
    <relation id="347824" visible="true" timestamp="2011-09-11T16:04:29Z" version="2" changeset="9272105" user="afernandez" uid="41263">
    <member type="node" ref="268521663" role="admin_centre"/>
    <member type="way" ref="45320004" role=""/>
    <member type="way" ref="45357913" role=""/>
    <member type="way" ref="45377654" role=""/>
    <member type="way" ref="45382632" role=""/>
    <member type="way" ref="45369688" role=""/>
    <tag k="admin_level" v="8"/>
    <tag k="boundary" v="administrative"/>
    <tag k="idee:name" v="Moratinos"/>
    <tag k="ine:municipio" v="34109"/>
    <tag k="is_in" v="Palencia, Castilla y Len, Spain"/>
    <tag k="is_in:country" v="Spain"/>
    <tag k="is_in:province" v="Palencia"/>
    <tag k="is_in:region" v="Castilla y Len"/>
    <tag k="name" v="Moratinos"/>
    <tag k="source" v="BDLL25, EGRN, Instituto Geogrfico Nacional"/>
    <tag k="type" v="boundary"/>
    <tag k="wikipedia" v="es:Moratinos"/>
    </relation>
            
     */
}