Example usage for org.dom4j Element addCDATA

List of usage examples for org.dom4j Element addCDATA

Introduction

In this page you can find the example usage for org.dom4j Element addCDATA.

Prototype

Element addCDATA(String cdata);

Source Link

Document

Adds a new CDATA node with the given text to this element.

Usage

From source file:XmlTestBuilder.java

License:Open Source License

protected Element createElement(Element parent, AST node) {
    Element result = parent.addElement("ast");
    int type = node.getType();
    String typeName = (String) tokens.get(new Integer(type));
    if (typeName == null) {
        result.addAttribute("type", Integer.toString(type));
    } else {/*from www  . j  av  a 2 s  .c  om*/
        result.addAttribute("name", typeName);
    }
    String text = node.getText();
    if (text != null) {
        if (text.indexOf('\n') == -1) {
            result.addAttribute("text", node.getText());
        } else {
            result.addCDATA(text);
        }
    }
    return result;
}

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

License:Apache License

/**
 * 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  ww .  j ava  2 s. c  om*/
 * 
 * <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:architecture.common.xml.XmlProperties.java

License:Apache License

/**
 * Sets the value of the specified property. If the property doesn't
 * currently exist, it will be automatically created.
 *
 * @param name//from w  w  w.java2  s.c  o 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:architecture.ee.util.xml.XmlProperties.java

License:Apache License

/**
 * 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:/*  w w w .ja v  a2  s  .c om*/
 * 
 * <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(XmlEscapers.xmlContentEscaper().escape(value));// 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.ee.util.xml.XmlProperties.java

License:Apache License

/**
 * Sets the value of the specified property. If the property doesn't
 * currently exist, it will be automatically created.
 *
 * @param name//  w ww .j av a 2s.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 (!XmlEscapers.xmlContentEscaper().escape(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:at.jabberwocky.impl.core.io.PacketReader.java

private Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
    DocumentFactory df = docFactory;/* w ww . j ava2  s .c  om*/
    Document document = df.createDocument();
    Element parent = null;
    XmlPullParser pp = parser;
    int count = 0;
    while (true) {
        int type = -1;
        type = pp.nextToken();
        switch (type) {
        case XmlPullParser.PROCESSING_INSTRUCTION: {
            String text = pp.getText();
            int loc = text.indexOf(" ");
            if (loc >= 0) {
                document.addProcessingInstruction(text.substring(0, loc), text.substring(loc + 1));
            } else {
                document.addProcessingInstruction(text, "");
            }
            break;
        }
        case XmlPullParser.COMMENT: {
            if (parent != null) {
                parent.addComment(pp.getText());
            } else {
                document.addComment(pp.getText());
            }
            break;
        }
        case XmlPullParser.CDSECT: {
            String text = pp.getText();
            if (parent != null) {
                parent.addCDATA(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have text content outside of the root document");
                }
            }
            break;

        }
        case XmlPullParser.ENTITY_REF: {
            String text = pp.getText();
            if (parent != null) {
                parent.addText(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have an entityref outside of the root document");
                }
            }
            break;
        }
        case XmlPullParser.END_DOCUMENT: {
            return document;
        }
        case XmlPullParser.START_TAG: {
            QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace())
                    : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
            Element newElement = null;
            // Do not include the namespace if this is the start tag of a new packet
            // This avoids including "jabber:client", "jabber:server" or
            // "jabber:component:accept"
            if ("jabber:client".equals(qname.getNamespaceURI())
                    || "jabber:server".equals(qname.getNamespaceURI())
                    || "jabber:component:accept".equals(qname.getNamespaceURI())
                    || "http://jabber.org/protocol/httpbind".equals(qname.getNamespaceURI())) {
                newElement = df.createElement(pp.getName());
            } else {
                newElement = df.createElement(qname);
            }
            int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
            int nsEnd = pp.getNamespaceCount(pp.getDepth());
            for (int i = nsStart; i < nsEnd; i++) {
                if (pp.getNamespacePrefix(i) != null) {
                    newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                }
            }
            for (int i = 0; i < pp.getAttributeCount(); i++) {
                QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i))
                        : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i),
                                pp.getAttributeNamespace(i));
                newElement.addAttribute(qa, pp.getAttributeValue(i));
            }
            if (parent != null) {
                parent.add(newElement);
            } else {
                document.add(newElement);
            }
            parent = newElement;
            count++;
            break;
        }
        case XmlPullParser.END_TAG: {
            if (parent != null) {
                parent = parent.getParent();
            }
            count--;
            if (count < 1) {
                return document;
            }
            break;
        }
        case XmlPullParser.TEXT: {
            String text = pp.getText();
            if (parent != null) {
                parent.addText(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have text content outside of the root document");
                }
            }
            break;
        }
        default:
        }
    }
}

From source file:cn.com.iscs.base.util.XMLProperties.java

License:Open Source License

/**
 * 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:// w  w w  .ja  v a2s  .  com
 * 
 * <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:cn.com.iscs.base.util.XMLProperties.java

License:Open Source License

/**
 * Sets the value of the specified property. If the property doesn't currently
 * exist, it will be automatically created.
 * //from   w  w  w . j  a  v a 2 s . c  o m
 * @param name
 *          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("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:com.collabnet.ccf.core.ga.GenericArtifactHelper.java

License:Open Source License

/**
 * Set the content of the element/*  w ww  .ja  v a 2s.  c  o m*/
 * 
 * @param element
 *            XML element
 * @param content
 *            content, encoded as String
 * @param useCDATASection
 *            if true, embed content into CDATA-section
 */
private static void setValue(Element element, String content, boolean useCDATASection) {
    if (useCDATASection)
        element.addCDATA(content);
    else
        element.setText(content);
}

From source file:com.dtolabs.client.services.JobDefinitionSerializer.java

License:Apache License

/**
 * Add script dispatch content to the job element
 *
 * @param dispatchdef dispatch definition
 * @param job         job element/*  ww w  .  j  a  va  2  s . com*/
 * @throws java.io.IOException if the input IDispatchedScript throws it when accessing script stream input.
 */
private static void addScriptDispatch(final IDispatchedScript dispatchdef, final Element job)
        throws IOException {
    if (null == dispatchdef.getFrameworkProject()) {
        throw new IllegalArgumentException("No project is specified");
    }
    final Element ctx = job.addElement("context");
    ctx.addElement("project").addText(dispatchdef.getFrameworkProject());
    final InputStream stream = dispatchdef.getScriptAsStream();
    final Element seq = job.addElement("sequence");
    final Element cmd = seq.addElement("command");
    if (null != dispatchdef.getScript() || null != stream) {

        //full script
        final Element script = cmd.addElement("script");
        if (null != dispatchdef.getScript()) {
            script.addCDATA(dispatchdef.getScript());
        } else {
            //serialize script inputstream and add string to dom
            final StringWriter sw = new StringWriter();
            copyReader(new InputStreamReader(stream), sw, 10240);
            sw.flush();
            script.addCDATA(sw.toString());
        }
        if (null != dispatchdef.getArgs() && dispatchdef.getArgs().length > 0) {
            final Element argstring = cmd.addElement("scriptargs");
            argstring.addText(OptsUtil.join(dispatchdef.getArgs()));
        }
    } else if (null != dispatchdef.getServerScriptFilePath()) {
        //server-local script filepath
        final Element filepath = cmd.addElement("scriptfile");
        filepath.addText(dispatchdef.getServerScriptFilePath());
        if (null != dispatchdef.getArgs() && dispatchdef.getArgs().length > 0) {
            final Element argstring = cmd.addElement("scriptargs");
            argstring.addText(OptsUtil.join(dispatchdef.getArgs()));
        }
    } else if (null != dispatchdef.getArgs() && dispatchdef.getArgs().length > 0) {
        //shell command
        final Element exec = cmd.addElement("exec");
        exec.addText(OptsUtil.join(dispatchdef.getArgs()));
    } else {
        throw new IllegalArgumentException("Dispatched script did not specify a command, script or filepath");
    }

}